Compiling and Linking

When you type gcc main.c util.c -o app, one command carries out four logical stages. Knowing these stages helps you locate build errors and explain why editing a header can cost more rebuild time than editing a source file. This lesson follows a C program from source text to an executable with the GNU toolchain.

Four stages behind one command

The gcc command is a compiler driver. It coordinates preprocessing, compilation proper, assembly and linking. These stages do not necessarily correspond to separate program invocations: GCC normally integrates preprocessing into its C compiler program, cc1. The standalone cpp command also provides preprocessing.


.c→preprocessing.i→compilation.s→assembly.o→linkingexecutable\texttt{.c} \xrightarrow{\text{preprocessing}} \texttt{.i} \xrightarrow{\text{compilation}} \texttt{.s} \xrightarrow{\text{assembly}} \texttt{.o} \xrightarrow{\text{linking}} \text{executable}


A pipeline diagram showing hello.c passing through preprocessing, compilation, assembly and linking to become the executable hello.


Preprocessing operates on preprocessing tokens and directives. It expands macros, includes header contents and selects code through conditional compilation directives such as #if. A source file together with its included contents, after preprocessing, forms a translation unit. In ordinary separate compilation, the compiler processes one translation unit at a time. Headers can supply declarations describing functions defined in other units.


The compiler checks syntax and types and emits assembly. The assembler produces an object file: machine code plus a symbol table and relocation information. A call to an external function can retain an unresolved reference. Running nm on an object file lists its symbols, with U marking undefined ones.


Stage

Representative implementation

Input and output

Stop here with

Typical error

Preprocessing

Integrated into cc1; standalone cpp

.c to .i

-E (standard output by default)

header not found

Compilation

cc1

.i to .s

-S

syntax and type errors

Assembly

as

.s to .o

-c

rare for compiler output

Linking

ld

.o files and libraries to executable

default, no stop option

undefined reference, multiple definition


Intermediate files need not be saved during an ordinary build.

What the linker does

The linker processes object files and libraries. In symbol resolution, it matches references to usable definitions. In relocation, it lays out code and data and patches references as needed. You name libraries with -l, so -lm requests libm, the math library. The option -L dir adds a library search directory, just as -I dir adds a header search directory.


With a static library (.a), needed object code is copied into the executable. With a shared library (.so), the code stays separate and the executable records a dependency. The dynamic loader loads the required shared libraries and supports runtime symbol resolution.



Separate compilation and rebuild cost

Compile source files to object files with -c, then link as a final step. This lets you reuse unchanged object files.


Shell
gcc -Wall -c main.c        # writes main.o
gcc -Wall -c util.c        # writes util.o
gcc main.o util.o -o app   # link only


After editing a .c file, recompile it and relink. After editing a header, recompile every source file that includes it, directly or through another header. Headers are normally included within translation units rather than separately compiled into ordinary object files; GCC also supports precompiled headers.


For sequential compilation followed by one link, ignoring other overhead, estimated elapsed time is


Trebuild=n tc+tℓT_{\text{rebuild}} = n\,t_c + t_\ell


Here nn counts recompiled translation units, tct_c is their average source-to-object compile time, and tℓt_\ell is the link time. Parallel builds require a different elapsed-time model because compilation tasks can overlap.


Example: With 40 source files, an average compile time of 0.5 s and a link time of 2.0 s, a full sequential build takes 40(0.5)+2.0=22.040(0.5) + 2.0 = 22.0 s. Recompiling one changed source file and relinking takes 0.5+2.0=2.50.5 + 2.0 = 2.5 s.



What to remember

  • gcc coordinates four logical stages; preprocessing is normally integrated into cc1. The options -E, -S and -c stop after preprocessing, compilation and assembly, respectively.
  • A translation unit contains one source file's preprocessed contents, including included headers.
  • Object files contain machine code, symbols and relocation information.
  • An undefined reference means no usable definition was resolved; check missing inputs and static-library order.
  • Sequential recompilation followed by one link takes approximately n tc+tℓn\,t_c + t_\ell, ignoring overhead. Header dependencies determine how many units need recompiling.

Example: Rebuilding a sensor-logging program

A data logger written in C has six source files: main.c, sensor.c, filter.c, display.c, storage.c and net.c. The header sensor.h is included by main.c, sensor.c, filter.c and display.c, and no other header includes it. On the development machine, compiling one source file to an object file takes 2.5 s on average, and linking all the object files takes 1.2 s.


a) Write the commands for a full build using separate compilation, and find the full-build time.


Compile each source file with -c, then link the object files in one final command:

  • gcc -Wall -c main.c, and the same for sensor.c, filter.c, display.c, storage.c and net.c
  • gcc main.o sensor.o filter.o display.o storage.o net.o -o logger

That is ________ compile commands and one link command. The compiles together take ________, and the link adds 1.2 s:


Tfull=6 tc+tℓ=6(2.5 s)+1.2 s=16.2 sT_{\text{full}} = 6\,t_c + t_\ell = 6(2.5\ \text{s}) + 1.2\ \text{s} = 16.2\ \text{s}


The full build takes 16.2 s.


b) You fix a bug inside a function in filter.c without touching any header. Which commands must run again, and how long does the rebuild take?


Only the translation unit built from filter.c changed, so ________ file is recompiled, with gcc -Wall -c filter.c. The other five object files are still current. The executable still contains the old code from filter.o, however, so the link command must run again.


T=1(2.5 s)+1.2 s=3.7 sT = 1(2.5\ \text{s}) + 1.2\ \text{s} = 3.7\ \text{s}


The rebuild takes 3.7 s, under a quarter of the full build.


c) You add a field to a structure declared in sensor.h. How long does the rebuild take now?


The header's text is part of every translation unit that includes it, and the new field changes the structure layout those files were compiled against. You must recompile main.c, sensor.c, filter.c and display.c, which is ________ files. The files storage.c and net.c do not include sensor.h, so their object files stay current. The compiles take ________, and the link runs once:


T=4(2.5 s)+1.2 s=11.2 sT = 4(2.5\ \text{s}) + 1.2\ \text{s} = 11.2\ \text{s}


The header edit costs 11.2 s, about three times the cost of the source-only edit in part b.


d) A teammate runs gcc main.o storage.o sensor.o filter.o display.o -o logger and gets undefined reference to 'net_send'. The function net_send is defined in net.c. Which stage failed, and what is the fix?


The command lists only object files, so preprocessing, compiling and ________ were already complete for every listed file. The error therefore comes from the linking stage. One of the listed object files calls net_send, so its symbol table holds an undefined reference. The only definition is in net.o, and the command never names that file.


The fix is to add the missing object file to the link command: gcc main.o storage.o sensor.o filter.o display.o net.o -o logger. No source file needs recompiling, so the fix costs one 1.2 s link.

A student runs gcc with no special options on a single C source file to produce an executable, and then runs the program. Put the steps in the order they happen, from source file to running program.

  1. 1.

    The linker resolves references against libraries and writes the executable file.

  2. 2.

    The assembler encodes the assembly as machine code in an object file.

  3. 3.

    The compiler translates the expanded C code into assembly language.

  4. 4.

    The loader maps the executable into memory when the program is run.

  5. 5.

    The preprocessor replaces each #include line with the header's text and expands macros.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Match each gcc command-line option with what it tells the GNU compiler driver to do when you build a C program.

Match each term
A.

Link against the library whose file name is lib followed by the given name

B.

Use the next argument as the name of the output file

C.

Stop after compiling and leave an assembly file ending in .s

D.

Stop after preprocessing and print the expanded source to standard output

E.

Add a directory to the list searched for header files

F.

Stop after assembling and leave an object file without linking

-E

-I

-S

-l

-c

-o

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

On a Linux system, each command below is run on its own in a directory that contains only calc.c, a complete C program with a main function. For each command, give the name of the output file gcc creates. Then name the last tool that runs, using exactly one of the words preprocessor, compiler, assembler or linker.

CommandOutput fileLast tool run
gcc -E calc.cprinted to terminal
gcc -S calc.c
gcc -c calc.c
gcc calc.c

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice