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
Inspect macro expansion, header inclusion and directives before the compiler parses the translation unit.
Preprocessing Pipeline
Inspecting the original source for simple macro.
#define PI 3.14159
#define SQUARE(x) ((x) * (x))
float area = PI * SQUARE(radius);float area = 3.14159 * ((radius) * (radius));Explanation: Macros are replaced with their definitions. Note the parentheses in SQUARE to ensure correct precedence.
g++ -E main.cpp -o main.i # Preprocess only
g++ -dM -E main.cpp # Show all defined macros
g++ -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
Macro Expansion Can Repeat Side Effects
- 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
constandconstexprover 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
Related concepts
Follow a C++ function from tokens to a simplified AST, then inspect exact source ranges, declaration references and types in a keyboard-accessible explorer.
Understand the complete C++ compilation pipeline from source code to object files. Learn preprocessing, parsing, code generation, and optimization stages.
Master C++ OOP concepts including inheritance, polymorphism, virtual functions, and modern object-oriented design principles with interactive examples.
How C++ object files are linked into executables. Learn symbol resolution, static vs dynamic linking, and linker optimization.
C++ compiler optimization lab notebook — compare optimization levels, inspect compiler rewrites, diagnose auto-vectorization, and build production verification commands.
Understand C++ pointers and references with step-by-step memory diagrams: addressing, dereferencing, aliasing, array arithmetic, and object lifetime.
