Modules (C++20)
Replacing headers with faster, cleaner imports
The Header Problem
Traditional headers are slow (textual inclusion) and fragile (macro leaks, include order matters).
// Old: Headers - slow, fragile
// math.h
#ifndef MATH_H // Include guards needed
#define MATH_H
namespace math {
double square(double x);
double cube(double x);
}
#endif
// C++20: Modules - fast, clean
// math.ixx (module interface unit)
export module math;
export namespace math {
double square(double x) { return x * x; }
double cube(double x) { return x * x * x; }
}
// main.cpp
import math; // Fast, no macros leaked
int main() {
auto result = math::square(5.0);
}Module Structure
// Module interface unit (math.ixx)
export module math;
// Import other modules
import std.core;
// Module implementation (can be in same file or separate)
module math;
// Private (not exported) - internal to module
namespace {
double internal_helper(double x) {
return x * 2;
}
}
// Exported interface
export double calculate(double x) {
return internal_helper(x) + 1;
}
// Export block
export {
struct Point { double x, y; };
double distance(Point a, Point b);
}Benefits
- ✓Faster compilation: Binary import, not textual inclusion
- ✓No macro leaks: Preprocessor isolated
- ✓Explicit exports: Clear public interface
- ✓No ODR violations: Same entity everywhere
Compiler Support
Modules require modern compiler support and build system configuration.
| Compiler | Status |
|---|---|
| GCC 11+ | Partial |
| Clang 16+ | Good |
| MSVC 2022 | Good |