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 outputThis 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:
-o: Outputs to a given filenamegcc source.c -o output g++ source.cpp -o output-c: Creates object file only, does not link.gcc -c source.c g++ -c source.cpp-S: Stops after the stage of compilation and does not assemble.gcc -S source.c g++ -S source.cpp-E: Stops after the preprocessing stage, does not compile.gcc -E source.c g++ -E source.cpp-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-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-l: Links with the library.gcc source.c -l library_name -o output g++ source.cpp -l library_name -o output-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-g: Generates debugging information. Useful for using with a debugger like gdb.gcc -g source.c -o output g++ -g source.cpp -o output-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.
-I: Specifies the path of the include files (headers).-L: Specifies the path of the library files.-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