CXX - yiliu30/yi GitHub Wiki

Common cmds

# https://bytes.usc.edu/cs104/wiki/gcc
# Compile a single program
g++ -Wall -g -std=c++17 test.cpp -o test

# Linking Multiple Files
gcc -o prog main.c sum.c

# Print all possible warning flags available to compile with
g++ --help=warnings

# Compile program using header files in ./include
# $(pwd) will expand to your current working directory
g++ -I /$(pwd)/include -Wall -g -std=c++17 test.cpp -o test

# Compile and optimize in parallel for helpful warnings about potential bugs
g++ -O2 -Wall -std=c++17 main.cpp -o main

Basic Usage of GCC

Command Structure

gcc [options] [input files] [output file]

Common Options

Compiling and Linking

  • gcc file.c: Compiles file.c and generates an executable a.out.
  • gcc -o output file.c: Compiles file.c and generates an executable named output.

Compilation Only

  • gcc -c file.c: Compiles file.c to an object file file.o without linking.

Linking Multiple Files

  • gcc -o output file1.c file2.c: Compiles file1.c and file2.c, and links them into a single executable named output.

Optimization Levels

  • -O0: No optimization (default).
  • -O1: Basic optimization.
  • -O2: Further optimization.
  • -O3: Maximum optimization.
  • -Os: Optimize for size.
  • -Og: Optimize for debugging.

Debugging Information

  • -g: Generates debug information to be used by GDB (GNU Debugger).

Warning and Error Messages

  • -Wall: Enables most warning messages.
  • -Werror: Treats warnings as errors.

Defining Macros

  • -Dname: Defines a macro name.
  • -Dname=value: Defines a macro name with the value value.

Include Directories

  • -I directory: Adds directory to the list of directories to be searched for header files.

Library Linking

  • -L directory: Adds directory to the list of directories to be searched for libraries.
  • -l library: Links with the library library.

Language Standards

  • -std=c89: Conforms to the ISO C89 standard.
  • -std=c99: Conforms to the ISO C99 standard.
  • -std=c11: Conforms to the ISO C11 standard.

Examples

Compile and Create an Executable

gcc -o myprogram main.c

Compile with Debugging Information

gcc -g -o myprogram main.c

Compile with Optimization

gcc -O2 -o myprogram main.c

Compile and Link Multiple Source Files

gcc -o myprogram main.c utils.c

Define a Macro and Include a Directory

gcc -DDEBUG -I./includes -o myprogram main.c

Linking with a Library

gcc -o myprogram main.c -L./lib -lmylib