C++ - Modules (C++20)
Overview
Estimated time: 45–65 minutes
Organize code with C++20 modules: faster builds, cleaner interfaces, and fewer macro/header pitfalls. Learn export/import basics, partitions, and build notes.
Learning Objectives
- Define a module interface and import it from a consumer.
- Use module partitions to split large interfaces.
- Understand practical build flags and migration tips.
Prerequisites
Minimal module
// math.ixx (module interface)
export module math;
export int add(int a,int b){ return a+b; }
// main.cpp (consumer)
import math;
#include
int main(){ std::cout << add(2,3) << "\n"; }
Partitioned module
// util.ixx
export module util;
export import :strings; // re-export partition
export int twice(int x){ return x*2; }
// util-strings.ixx (partition)
module util:strings;
export const char* greet(){ return "hello"; }
Build notes
- Compilers use special flags for scanning/compiling modules (varies by vendor and build system).
- Prefer using a modern CMake (3.26+) with modules support and toolchain integration.
- Avoid textual includes in module interfaces when possible; import standard libraries as they become modularized.
Common Pitfalls
- Mixing headers and modules without clear boundaries can cause ODR or visibility issues.
- Macros do not cross module boundaries; avoid relying on header-based macro tricks.
Checks for Understanding
- What is exported in a module interface?
- When would you use a partition?
Show answers
- Only declarations marked with
export
are visible to importers. - To split a large interface into logical parts while keeping a single module name.
Exercises
- Create a small math module with add/sub/mul and import in a main program.
- Add a partition for string helpers and re-export it from the main module.