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.
Key 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
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
Explore how C++ code is parsed into an Abstract Syntax Tree (AST). Learn lexical analysis, tokenization, and syntax parsing for systems programming.
Understand the complete C++ compilation pipeline from source code to object files. Learn preprocessing, parsing, code generation, and optimization stages.
Explore CPython bytecode compilation from source to .pyc files. Learn the dis module, PVM stack operations, and Python 3.11+ adaptive specialization.
How C++ object files are linked into executables. Learn symbol resolution, static vs dynamic linking, and linker optimization.
Explore modern C++ features including auto, lambdas, ranges, and coroutines. Learn how C++11/14/17/20 transformed the language.
Master C++ OOP concepts including inheritance, polymorphism, virtual functions, and modern object-oriented design principles with interactive examples.
