Skip to content

Modules (C++20)

In a Nutshell

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

Headers

None (Language feature, uses new file types and keywords)

Core API Cheat Sheet

SyntaxDescription
module;Start of the global module fragment (for preprocessor directives like #include)
export module ModuleName;Declare a module interface unit, exporting the module name ModuleName
exportExport declaration, making it visible to module consumers
module ModuleName;Module implementation unit (internal, does not export)
import ModuleName;Import a module (replaces #include)
export import SubModule;Re-export a submodule
module :private;Private module fragment (C++20), implementation details not part of the module interface

Minimal Example

cpp
// math_utils.cppm
export module math_utils;  // Declare module interface

namespace math {
    export constexpr int add(int a, int b) { // Exported function
        return a + b;
    }
}

// main.cpp
import math_utils;        // Import module
import std;               // Import standard library module (if supported)

int main() {
    return math::add(1, 2);
}

Embedded Applicability: Medium

  • Compilation Speed: Module interfaces are compiled once and cached, reducing recompilation time for large projects by 30-70%.
  • Macro Isolation: #define macros outside the module boundary do not leak into the module, improving build stability.
  • Symbol Visibility: export explicitly controls API boundaries, replacing the "everything is public" nature of headers.
  • Build System Support: Native CMake support for modules is gradually maturing in version 3.28+.
  • Compatibility: Compiler implementations vary (BMI formats are not universal), so cross-compiler builds require caution.
  • Embedded Toolchains: Support for modules in embedded toolchains (especially cross-compilation scenarios) lags behind; short-term adoption in core embedded projects is not recommended.

Compiler Support

GCCClangMSVC
111619.28

See Also


Parts of the content referenced from cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05