C++ Compilation Overview

5 min

Understand the complete C++ compilation pipeline from source code to object files.

Best viewed on desktop for optimal interactive experience

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

Source Code
main.cpp
Preprocessing
main.i
Parsing
AST
Semantic Analysis
Annotated AST
IR Generation
IR
Optimization
Optimized IR
Code Generation
main.s
Assembly
main.o

Typical File Sizes

.cpp
~1KB
.i
~50KB
AST
~20KB
IR
~15KB
.s
~5KB
.o
~2KB

Compilation Stages

Each stage transforms your code closer to machine language:

1. Preprocessing

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

2. Parsing & AST

  • 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

  • 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

# 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?

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