Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

🏠 Back to Blog

The 4 Steps of Compilation with GCC

GCC transforms source code into an executable file through four primary steps:


1. Preprocessing

  • What happens:
    • The preprocessor handles directives in the source code (e.g., #include, #define, #ifdef).
    • It replaces macros, includes header files, and resolves conditional compilation directives.
  • Input: .c source file.
  • Output: A preprocessed source file (usually with a .i or .ii extension).
  • Command:
    gcc -E file.c -o file.i
    
  • Example:
    • Converts:
      #include <stdio.h>
      #define PI 3.14
      printf("PI is %f\n", PI);
      
      Into:
      // Expanded header contents of stdio.h
      printf("PI is %f\n", 3.14);
      

2. Compilation

  • What happens:
    • The compiler translates the preprocessed source code into assembly language, specific to the target architecture.
  • Input: Preprocessed source file (.i or .ii).
  • Output: Assembly file (usually with a .s extension).
  • Command:
    gcc -S file.i -o file.s
    
  • Example:
    • Converts preprocessed code into assembly instructions like:
      movl $3.14, -4(%ebp)
      call printf
      

3. Assembly

  • What happens:
    • The assembler translates the assembly code into machine code, creating an object file.
  • Input: Assembly file (.s).
  • Output: Object file (.o or .obj).
  • Command:
    gcc -c file.s -o file.o
    
  • Example:
    • Produces a binary object file containing machine instructions that the CPU can execute.

4. Linking

  • What happens:
    • The linker combines object files and libraries to create an executable program.
    • Resolves symbols (e.g., function calls, global variables) across different object files.
  • Input: One or more object files (.o) and optional libraries.
  • Output: Executable file (e.g., a.out by default).
  • Command:
    gcc file.o -o file
    
  • Example:
    • Combines multiple .o files and links to the standard C library (libc) to produce a runnable executable.

Full Process with GCC

Running GCC without intermediate steps performs all four stages automatically:

gcc file.c -o file