Modules (C++20)
The problem with #include
export module and import
A minimal module (math.ixx / math.cppm) and its consumer
// math.ixx -- the module interface file
export module math;
export int square(int x) {
return x * x;
}
export int cube(int x) {
return x * x * x;
}
// -----------------------------------------------------------------
// main.cpp -- consuming the module
import math;
#include <iostream>
int main() {
std::cout << square(5) << "\n"; // 25
std::cout << cube(3) << "\n"; // 27
return 0;
}Aspect | Headers (#include) | Modules (import) |
|---|---|---|
Processing | Re-parsed textually in every including file | Compiled once into a binary interface, then reused |
Macro leakage | Macros can leak across include boundaries | Macros do not leak out of a module by default |
Multiple inclusion | Requires include guards / #pragma once | Not an issue -- importing twice is safe by design |
Compile times | Grow with repeated header re-parsing | Generally faster on large codebases |
Current state of adoption
The header + #include system is textual, re-parsed repeatedly, and prone to macro leakage and ordering issues.
export module declares a module; import consumes it, with no textual copy-pasting involved.
Modules are compiled once into a reusable binary interface, which can meaningfully speed up large builds.
Modules are a newer, still-maturing feature -- verify your compiler and build system support before adopting them.