C++ Preprocessor
Master the C++ preprocessor with interactive visualizations of macros, includes, and conditional compilation.
Best viewed on desktop for optimal interactive experience
The C++ Preprocessor
The preprocessor is your first line of code transformation, running before compilation begins. It handles macros, includes, and conditional compilation through simple text substitution.
C++ Preprocessor Visualizer
Preprocessing Pipeline
??=
Trigraph Replacement
Legacy character replacement
\
Line Splicing
Join continued lines
[ ]
Tokenization
Break into tokens
#
Macro Expansion
Replace macros
<>
Include Processing
Insert header files
#if
Conditional Compilation
Process conditionals
Original Code
#define PI 3.14159
#define SQUARE(x) ((x) * (x))
float area = PI * SQUARE(radius);
After Preprocessing
float area = 3.14159 * ((radius) * (radius));
💡 Explanation: Macros are replaced with their definitions. Note the parentheses in SQUARE to ensure correct precedence.
Preprocessor Commands
g++ -E main.cpp -o main.i
Preprocess onlyg++ -dM -E main.cpp
Show all defined macrosg++ -H main.cpp
Show included headersKey Directives
Macros (#define)
#define PI 3.14159 #define SQUARE(x) ((x) * (x)) #define MAX(a,b) ((a) > (b) ? (a) : (b))
Include Guards
#ifndef HEADER_H #define HEADER_H // Header content #endif // Or modern: #pragma once
Conditional Compilation
#ifdef DEBUG #define LOG(x) std::cout << x #else #define LOG(x) #endif
Common Pitfalls
- Missing parentheses:
#define DOUBLE(x) x * 2
→ Use((x) * 2)
- Side effects:
SQUARE(i++)
expands to((i++) * (i++))
- Name collisions: Macros are global, use unique names
Best Practices
- Prefer
const
andconstexpr
over macros - Use ALL_CAPS for macro names
- Always parenthesize macro parameters
- Document macro behavior
- Consider inline functions instead
Next Steps
- Explore AST & Parsing
- Learn about Compilation Pipeline
- Master Templates for type-safe alternatives