Skip to content

Modules (C++20) ​

In a Nutshell ​

Replace header files with module interface files (.cppm)—compile once, cache the result, and dramatically speed up recompilation, while isolating macro pollution and providing genuine control over symbol visibility.

None (a language feature that uses new file types and keywords)

Core API Cheat Sheet ​

SyntaxDescription
module;Start of the global module fragment (holds preprocessor directives such as #include)
export module mylib;Declares a module interface unit, exporting the module name mylib
export int func();Exported declaration, visible to users of the module
module mylib;Module implementation unit (not exported, implementation only)
import mylib;Imports a module (replaces #include)
export import :sub;Re-exports a submodule
module :private;Private module fragment (C++20); implementation details are not part of the module interface

Minimal Example ​

C++
// Standard: C++20
// --- math.cppm (module interface) ---
export module math;

export int add(int a, int b) {
    return a + b;
}

// --- main.cpp (consumer) ---
import math;
#include <iostream>

int main() {
    std::cout << add(2, 3) << "\n"; // 5
}

Embedded Applicability: Medium ​

  • Faster builds: module interfaces are compiled once and cached, cutting recompilation time on large projects by 30-70%
  • Macro isolation: #define outside the module boundary cannot leak into the module, improving build stability
  • Symbol visibility: export explicitly controls the API boundary, replacing the "everything is public" model of header files
  • Build system support is still immature: CMake's native support for modules has been gradually maturing in 3.28+
  • Compiler implementations have compatibility issues (module BMI formats are not interoperable), so cross-compiler builds require caution
  • Embedded toolchains (especially cross-compilation scenarios) lag behind in module support; short-term adoption in the core of embedded projects is not recommended

Compiler Support ​

GCCClangMSVC
111619.28

See Also ​


Some content is referenced from cppreference.com, used under the CC-BY-SA 4.0 license

pdf-latest-4-g85128cc · 85128cc · 2026-10-05