6.1. Compiling programs

Programmers using Linux compile programs with the GNU Compiler Collection (GCC), a “compiler driver that invokes the language preprocessor, compiler, assembler, and linker, as needed on behalf of the user.”[42] A list of commonly used compiler flags (which are options to adjust the compiler’s behavior) is provided in Table 6.1, “Commonly used GCC flags”. For a listing of all of the available flags, see man gcc or info gcc under the section “Invoking GCC.

To compile C source code or assembly programs with GCC, type: gcc [flags] file_list.

[Note]Note

When you are compiling C++ source code, type g++ in place of gcc.

If you don't specify a file name for the resulting executable file using the -o compiler flag, GCC will use the default name of a.out.

Although you can use GCC directly to compile your programs, programmers typically use other software, such as GNU Make, for automating the build process. A discussion of Make is beyond the scope of this guide, but references to more information on Make are provided in Section A.5.3, “GNU Make and Makefiles”.

References to further reading on GCC can be found in Section A.5.2, “More on GCC”.

Example 6.1. Using GCC

gcc -Wall -o foo foo.c will attempt to compile foo.c to an executable, turning on (nearly) all compiler warnings, producing the executable foo if it is successful.


Table 6.1. Commonly used GCC flags

Compiler FlagAction
-cCompile to object code and then stop
-gInclude debugging information
-ggdbInclude extra debugging information for GDB[a]
-I dirCheck first for header files in directory dir[b]
-L dirCheck first for libraries in directory dir[c]
-o nameSet the (file) name of the compiler's output
-O2Use the optimizer at level 2
-SCompile to assembly code and then stop
-WallTurn on all compiler warnings[d]

[b] (can use this flag repeatedly to specify multiple directories)

[c] (can use this flag repeatedly to specify multiple directories)

[d]

Well, -Wall will actually turn on most compiler warnings.
To find out which warnings are enabled by -Wall, check man gcc.




[42] Randal Bryant and David O'Hallaron, Computer Systems: A Programmer's Perspective (Upper Saddle River: Prentice Hall, 2003), 541.


Back to Guide main page