Modules
C++20 Modules
Section titled “C++20 Modules”C++20 introduced modules as a modern replacement for header files.
Problems with Headers
Section titled “Problems with Headers”┌─────────────────────────────────────────────────────────────┐│ Headers vs Modules │├─────────────────────────────────────────────────────────────┤│ ││ Headers (.h) | Modules (.cppm) ││ ───────────────────── | ────────────────────── ││ • Text inclusion | • Single compilation ││ • Macro pollution | • No macro issues ││ • Rebuild everything | • Faster builds ││ • No encapsulation | • True encapsulation ││ │└─────────────────────────────────────────────────────────────┘Basic Module
Section titled “Basic Module”export module math;
export int add(int a, int b) { return a + b;}
export int multiply(int a, int b) { return a * b;}Importing Modules
Section titled “Importing Modules”import math;
int main() { int result = add(5, 3); return 0;}Module Partitions
Section titled “Module Partitions”// math.cppm (primary module interface)export module math;
export int add(int a, int b);
// Implementation partitionmodule math.implementation;
int helper(int x) { return x * 2;}Benefits
Section titled “Benefits”- Faster compilation
- No header guards needed
- True encapsulation
- No macro pollution
Key Takeaways
Section titled “Key Takeaways”- Modules replace headers in modern C++
- Use
.cppmextension for module interfaces - Provides better encapsulation and faster builds