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.
- The preprocessor handles directives in the source code (e.g.,
- Input:
.csource file. - Output: A preprocessed source file (usually with a
.ior.iiextension). - Command:
gcc -E file.c -o file.i - Example:
- Converts:
Into:#include <stdio.h> #define PI 3.14 printf("PI is %f\n", PI);// Expanded header contents of stdio.h printf("PI is %f\n", 3.14);
- Converts:
2. Compilation
- What happens:
- The compiler translates the preprocessed source code into assembly language, specific to the target architecture.
- Input: Preprocessed source file (
.ior.ii). - Output: Assembly file (usually with a
.sextension). - Command:
gcc -S file.i -o file.s - Example:
- Converts preprocessed code into assembly instructions like:
movl $3.14, -4(%ebp) call printf
- Converts preprocessed code into assembly instructions like:
3. Assembly
- What happens:
- The assembler translates the assembly code into machine code, creating an object file.
- Input: Assembly file (
.s). - Output: Object file (
.oor.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.outby default). - Command:
gcc file.o -o file - Example:
- Combines multiple
.ofiles and links to the standard C library (libc) to produce a runnable executable.
- Combines multiple
Full Process with GCC
Running GCC without intermediate steps performs all four stages automatically:
gcc file.c -o file