Skip to main content

C++ Compilation Overview

Understand the complete C++ compilation pipeline from source code to object files. Learn preprocessing, parsing, code generation, and optimization stages.

The Compilation Pipeline

Every C++ program goes through multiple transformation stages before becoming executable machine code. This overview shows the complete pipeline:

C++ Compilation Pipeline

Follow one translation unit from source text to an object file. Select a stage to inspect its input and output.

Step 1 / 8

Source Code: Human-readable C++ code

Illustrative File Sizes

.cpp~1 KB
.i~50 KB
AST~20 KB
IR~15 KB
.s~5 KB
.o~2 KB
File sizes are illustrative, not measured compiler output. Their relative sizes depend on the source, headers, compiler and flags.

Compilation Stages

Each stage transforms your code closer to machine language:

1. Preprocessing

The preprocessor rewrites the source text before the compiler proper sees it:

  • Macro expansion
  • Include processing
  • Conditional compilation
  • Output: Expanded source (.i file)

2. Parsing & AST

The parser turns the token stream into an abstract syntax tree:

  • Lexical analysis (tokenization)
  • Syntax analysis (parsing)
  • Build Abstract Syntax Tree
  • Output: AST representation

3. Semantic Analysis

  • Type checking
  • Name resolution
  • Template instantiation
  • Output: Annotated AST

4. Optimization

The optimizer rewrites the intermediate representation:

  • Code improvements
  • Performance enhancements
  • Size reductions
  • Output: Optimized IR

5. Code Generation

  • Target-specific assembly
  • Register allocation
  • Instruction selection
  • Output: Assembly (.s file)

6. Assembly

  • Convert to machine code
  • Create object file
  • Output: Object file (.o)

Quick Commands

bash
# Complete compilation
g++ main.cpp -o program

# Stop after preprocessing
g++ -E main.cpp -o main.i

# Generate assembly
g++ -S main.cpp -o main.s

# Create object file only
g++ -c main.cpp -o main.o

# With optimization
g++ -O2 main.cpp -o program

Compilation Deep Dives

Explore each stage in detail:

What's Next?

Object Files Need Linking and Loading

After compilation, your object files need to be:

  1. Linked together to resolve symbols
  2. Loaded into memory for execution

If you found this explanation helpful, consider sharing it with others.

Mastodon