Skip to content

Modules

C++20 introduced modules as a modern replacement for header files.

┌─────────────────────────────────────────────────────────────┐
│ Headers vs Modules │
├─────────────────────────────────────────────────────────────┤
│ │
│ Headers (.h) | Modules (.cppm) │
│ ───────────────────── | ────────────────────── │
│ • Text inclusion | • Single compilation │
│ • Macro pollution | • No macro issues │
│ • Rebuild everything | • Faster builds │
│ • No encapsulation | • True encapsulation │
│ │
└─────────────────────────────────────────────────────────────┘
math.cppm
export module math;
export int add(int a, int b) {
return a + b;
}
export int multiply(int a, int b) {
return a * b;
}
main.cpp
import math;
int main() {
int result = add(5, 3);
return 0;
}
// math.cppm (primary module interface)
export module math;
export int add(int a, int b);
// Implementation partition
module math.implementation;
int helper(int x) {
return x * 2;
}
  • Faster compilation
  • No header guards needed
  • True encapsulation
  • No macro pollution
  • Modules replace headers in modern C++
  • Use .cppm extension for module interfaces
  • Provides better encapsulation and faster builds