1. Problem It Solves
Modules provide named compiled interfaces that avoid textual header inclusion and separate exported API from hidden implementation. It makes an important assumption visible and checkable.
2. Prerequisites
Separate translation units, declarations, definitions, and linking.
You should be able to compile a short program and read its output.
3. Core Idea
The interface is a service counter, the implementation is the back room, and an importer sees only what the counter explicitly exports. Read export module as a precise promise; runtime preconditions still belong to the programmer.
4. Minimal Syntax
export module math;
export int add(int, int);5. How It Works
The program introduces the smallest relevant form of
export module.It applies the feature to fixed data while required owners remain in scope.
It prints one result that can be checked against the source.
6. Common Mistakes
A real module requires multiple translation units and compiler-specific build ordering; placing interface, implementation, and importer in one ordinary source is not a real module build.
Also check the required header, C++20 library support, lifetime, and deduced types.
7. When to Use It
Use it when a project and toolchain can manage module dependency scanning and stable interface boundaries.
Avoid it when a tiny portable example must be built as one ordinary translation unit.
8. Simple Example
Because this course requires one runnable .cpp per day, the program prints the three exact source fragments needed for a real multi-file module. The companion .cpp uses no input, so its result is easy to reproduce.
Complete sample code
Source file
cpp20/26_modules_interface_implementation_import/main.cpp
// Day 26: Module Interfaces, Implementation Units, and import
#include <array>
#include <iostream>
#include <string_view>
int main() {
constexpr std::array<std::string_view, 3> units{
"export module math;\nexport int add(int, int);",
"module math;\nint add(int a, int b) { return a + b; }",
"import math;\nint main() { return add(2, 3) != 5; }"
};
constexpr std::array labels{"interface", "implementation", "importer"};
for (std::size_t i = 0; i < units.size(); ++i) {
std::cout << "[" << labels[i] << "]\n" << units[i] << "\n\n";
}
}
9. Key Takeaways
export moduleexpresses the central C++20 idea of this day.The example isolates one behavior with fixed data.
Compiler checks do not replace lifetime and runtime reasoning.
Prefer the smallest interface that states the real requirement.
10. Self-Check Questions
Easy — What is the main job of
export modulein the minimal example?Medium — Which declaration makes
addvisible to an importing translation unit?Hard — Why must the interface unit be compiled before an importer even though final symbol resolution still involves the linker?