gcc & g++

GCC & G++: GNU Compiler Collection

The GNU Compiler Collection (GCC) and G++ are command-line compilers for C and C++ respectively. They turn source code into executable programs.

Basics: GCC and G++ follow the same syntax:

gcc [options] source.c -o output
g++ [options] source.cpp -o output

This command will compile the source code from 'source.c' or 'source.cpp' into an executable named 'output'. If '-o output' is not provided, it will output 'a.out' by default.

Common Switches:

  1. -o : Outputs to a given filename

    gcc source.c -o output
    g++ source.cpp -o output
  2. -c : Creates object file only, does not link.

    gcc -c source.c
    g++ -c source.cpp
  3. -S : Stops after the stage of compilation and does not assemble.

    gcc -S source.c
    g++ -S source.cpp
  4. -E : Stops after the preprocessing stage, does not compile.

    gcc -E source.c
    g++ -E source.cpp
  5. -I : Specifies an include directory, where the compiler can find header files.

    gcc -I path/to/headers source.c -o output
    g++ -I path/to/headers source.cpp -o output
  6. -L : Specifies a library directory, where the compiler can find library files.

    gcc -L path/to/library source.c -o output
    g++ -L path/to/library source.cpp -o output
  7. -l : Links with the library.

    gcc source.c -l library_name -o output
    g++ source.cpp -l library_name -o output
  8. -Wall : Enables all compiler's warning messages. This switch is helpful for debugging.

    gcc -Wall source.c -o output
    g++ -Wall source.cpp -o output
  9. -g : Generates debugging information. Useful for using with a debugger like gdb.

    gcc -g source.c -o output
    g++ -g source.cpp -o output
  10. -std : Specifies the standard of C or C++ to use.

    gcc -std=c99 source.c -o output
    g++ -std=c++11 source.cpp -o output

Including Libraries:

Libraries can be included using -I, -L, and -l switches.

  1. -I: Specifies the path of the include files (headers).

  2. -L: Specifies the path of the library files.

  3. -l: Specifies the name of the library to link with.

If you had a library named 'libfoo' located at '/path/to/lib' and the corresponding header files located at '/path/to/include', you would compile your program 'program.c' which uses this library like so:

In this command, libfoo.so (shared object) or libfoo.a (static library) will be linked.

Note that -l expects the library name without the 'lib' prefix and the file extension. Thus, libfoo.so or libfoo.a becomes just 'foo'

Last updated