C Compiler & Linking Process

C Compiler & Linking Process
C Compiler & Linking Process programs go through several stages before becoming an executable. Understanding this helps in debugging, organizing code, and optimizing compilation.
C Program Compilation Stages
When you run gcc program.c, the process generally involves 4 main stages:
Preprocessing
Compilation
Assembly
Linking
1️⃣ Preprocessing
Handled by C Preprocessor (
cpp)Processes all preprocessor directives starting with
#, like#include,#defineRemoves comments, expands macros, and includes header files
Example:
After preprocessing, the code becomes:
✅ Output: .i file (optional, you can see it with gcc -E program.c -o program.i)
2️⃣ Compilation
Converts preprocessed C code into assembly code
Checks syntax, type errors, and generates assembly instructions
✅ Output: .s file (assembly code)
Example: gcc -S program.c → program.s
3️⃣ Assembly
Converts assembly code into machine code (object file)
Generates
.o(or.obj) file
Example: gcc -c program.c → program.o
4️⃣ Linking
Combines one or more object files and library code into executable
Resolves symbols (variables/functions used in one file but defined in another)
Includes standard libraries like
libc
Example:
Output:
program(executable)
Multi-File Project Example
math_utils.c
main.c
Compilation Steps:
Compilation Options (GCC)
| Option | Purpose |
|---|---|
-E | Preprocessing only |
-S | Compile to assembly |
-c | Compile to object file (no linking) |
-o filename | Specify output file name |
-Wall | Enable all warnings |
Linking Types
Static Linking
Libraries are included in executable at compile-time
Larger executable, independent of system libraries
Dynamic Linking
Libraries loaded at runtime (
.soin Linux,.dllin Windows)Smaller executable, system library must exist
🧠 Key Points
Each stage produces intermediate files (
.i,.s,.o)Linking resolves external symbols between files
Understanding compilation helps debug build errors and optimize programs
