Compiling
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.”[43] 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 | |
---|---|
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 Flag | Action |
---|---|
-c | Compile to object code and then stop |
-g | Include debugging information |
-ggdb | Include extra debugging information for GDB[a] |
-I dir | Check first for header files in directory dir [b] |
-L dir | Check first for libraries in directory dir [c] |
-o name | Set the (file) name of the compiler's output |
-O2 | Use the optimizer at level 2 |
-S | Compile to assembly code and then stop |
-Wall | Turn on all compiler warnings[d] |
[a] GDB is discussed in Section 6.3, “Debugging programs”. [b] (can use this flag repeatedly to specify multiple directories) [c] (can use this flag repeatedly to specify multiple directories) [d] Well, |
[43] Randal Bryant and David O'Hallaron, Computer Systems: A Programmer's Perspective (Upper Saddle River: Prentice Hall, 2003), 541.