Skip to content

GCC

How GCC turns a C file into a program in four stages, preprocessing, compiling, assembling and linking, and how to stop after each one.

2 min readUpdated

Compilation translates source code, the code we write, into object code: a sequence of machine language instructions. When you run gcc main.c, GCC actually runs four tools one after the other, and each stage’s output is the next stage’s input:

  1. The preprocessor expands #include and #define directives and removes comments.
  2. The compiler translates the preprocessed C into assembly code for the target processor.
  3. The assembler turns the assembly code into an object file (.o) with machine code.
  4. The linker combines the object files with the libraries they use into an executable.

The diagram shows the flow from the source file to the executable.

The compilation process: a .c source file passes through the preprocessor and the compiler to assembly code, the assembler produces an object file, and the linker combines it with libraries into an executable

GCC can stop after any stage, which helps when you want to see what a macro expands to or what code the compiler generates. The examples use a single file main.c.

Preprocess only

-E runs only the preprocessor and writes the result to standard output:

Terminal window
gcc -E main.c

Save it to a file with -o; .i is the usual extension for preprocessed C:

Terminal window
gcc -E main.c -o main.i

The output is long, because the contents of every included header are copied in.

Compile to assembly

-S stops after the compiler and writes the assembly code to main.s:

Terminal window
gcc -S main.c

Assemble to an object file

-c compiles and assembles, but does not link. The result is the object file main.o:

Terminal window
gcc -c main.c

Object files are what larger projects build per source file; only the last step links them together.

Without any of these options, GCC runs all four stages. The executable is called a.out by default:

Terminal window
gcc main.c
./a.out

-o gives the executable a name:

Terminal window
gcc main.c -o my_program
./my_program

Several source or object files are linked into one program by listing them all. Libraries are added with -l; for example, programs that use math.h functions need -lm on Linux:

Terminal window
gcc main.c util.c -o my_program -lm

To keep the intermediate files of every stage (.i, .s and .o) from a normal build, add -save-temps.

References

Related notes

2 min read

ngrok

Expose a local web server on a public HTTPS address with ngrok, for webhook testing, demos and testing on real devices.

  • Developer Tools
2 min read

NetBeans

Build Apache NetBeans from source, clear the Recent Projects list and choose the JDK the IDE runs on.

  • Developer Tools
3 min read

Vim and Neovim

Set up Vim with VimTeX and Zathura for LaTeX on macOS, and add the Neo-tree file explorer to Neovim.

  • Developer Tools

Type to search the whole site.