next up previous contents
Next: Optimization Options Up: Compiling with GCC Previous: Compiling with GCC   Contents


Compiling a Single Source File

To compile a C source file, you use the -c option.
% gcc -c main.c
To tell GCC to stop compilation after preprocessing, use GCC's -E option:
% gcc -E main.c -o main.pp
Examine main.pp and you can see the contents of stdio.h, stdlib.h and reciprocal.hpp have indeed been inserted into the file, along with other preprocessing tokens. The next step is to compile main.pp to object code. Use GCC's -c option to accomplish this:
%gcc -x cpp-output -c main.pp -o main.o
The most common extensions and their interpretation are listed in Table 1.1.

Table 1.1: How GCC interprets filename extensions.
Extension Type
.c C language source code
.C, .cc C++ language source code
.i Preprocessed C source code
.ii Preprocessed C++ source code
.S, .s Assembly language source code
.o Compiled object code
.a, .so Compiled library code

The resulting object file is named main.o. The C++ compiler is called g++.

% g++ -c reciprocal.cpp
The -c option tells g++ to compile the program to an object file only; without it, g++ will attempt to link the program to produce an executable. After you've typed this command, you'll have an object file called reciprocal.o.

The -I option is used to tell GCC where to search for header files. By default, GCC looks in the current directory and in the directories where headers for the standard libraries are installed. If you need to include header files from somewhere else, you'll need the -I option.

% g++ -c -I ../include reciprocal.cpp
If you don't want the overhead of the assertion check present in reciprocal.cpp; that's only there to help you debug the program.You turn off the check by defining the macro NDEBUG.
% g++ -c -D NDEBUG reciprocal.cpp
If you had wanted to define NDEBUG to some particular value, you could have done something like this:
% g++ -c -D NDEBUG=3 reciprocal.cpp
If you are really building production code, you probably want to have GCC optimize the code so that it runs as quickly as possible.You can do this by using the -O2 command-line option. Static variables may vanish or loops may be unrolled, so that the optimized program does not correspond line-for-line with the original source code. (GCC has several different levels of optimization; the second level is appropriate for most programs.)
% g++ -c -O2 reciprocal.cpp
Note that compiling with optimization can make your program more difficult to debug with a debugger. Also, in certain instances, compiling with optimization can uncover bugs in your program that did not manifest themselves previously.
next up previous contents
Next: Optimization Options Up: Compiling with GCC Previous: Compiling with GCC   Contents
Cem Ozdogan 2007-05-16