`module` — C++ Keyword

`module` — C++ Keyword

The module keyword in C++20: declares or introduces a named module.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

module

Declares the current translation unit as a module unit in C++20's module system. Modules replace #include-based code sharing with an explicit, faster, and more hygienic mechanism.

Syntax

module;                        // global module fragment (for #includes)
export module name;            // primary module interface unit
module name;                   // module implementation unit
export module name : partition; // module partition interface
module name : partition;        // module partition implementation

Example

// --- math.cppm (module interface unit) ---
export module math;

export int add(int a, int b) { return a + b; }
export double square(double x) { return x * x; }

// --- main.cpp ---
import math;
#include <print>

int main() {
    std::println("{}", add(3, 4));       // 7
    std::println("{:.1f}", square(5.0)); // 25.0
}

Notes

Example in practice

int main() {
    // Pick one facility from this reference page.
    // Write the smallest program that exercises its main precondition,
    // complexity rule, or lifetime constraint before scaling up.
    return 0;
}