Modules (C++20)

Modules (C++20) in C++: Replace textual inclusion with a compiled, sealed interface. For forty years, sharing C++ code has worked like this: you keep your…

Replace textual inclusion with a compiled, sealed interface.

The Analogy: A Sealed Component Instead of a Pile of Photocopies

For forty years, sharing C++ code has worked like this: you keep your declarations in a header, and every file that wants them says #include, which means paste the entire text of that file in here. The compiler then re-reads and re-parses those thousands of lines for every single translation unit that asked. A hundred files including <iostream> is a hundred separate readings of tens of thousands of lines.

Worse, a photocopy carries everything on the page. Macros you defined leak out and rewrite the including file's code. Anything you put in the header — helper functions, private types, a #define NDEBUG — becomes part of your public surface whether you meant it or not. And because the paste happens at the point of inclusion, the order of your includes can change what compiles.

A module is a sealed component instead. You describe its interface once, the compiler builds it once into a binary form, and every consumer that says import gets that prepared interface handed to it — parsed, checked, and complete. Nothing leaks out except what you explicitly export. Macros stay inside. Order stops mattering.

The idea is not new — most languages have had it for decades. What is new is having it in C++ without giving up templates, headers, or existing code.


Syntax or Core Structure

A module lives in one or more module units. The smallest useful version is a single interface file:

// ---------- mathutils.cppm : a module interface unit ----------
export module mathutils;                 // this file declares the module

// The global module fragment: where #includes go, if you need them.
// (Shown below in the fuller example -- it must come BEFORE the module line.)

export int square(int n) { return n * n; }      // visible to importers
export int cube(int n) { return n * n * n; }

int helper(int n) { return n + 1; }             // NOT exported: module-private

export namespace geometry {                     // export a whole namespace
    inline int perimeter(int w, int h) { return 2 * (w + h); }
}

export {                                        // or a whole block
    int doubled(int n) { return n * 2; }
    int halved(int n)  { return n / 2; }
}
// ---------- main.cpp : a consumer ----------
#include <iostream>
import mathutils;                        // one line, no path, no guard

int main() {
    std::cout << square(7) << " " << cube(3) << "\n";
    std::cout << geometry::perimeter(4, 5) << " " << doubled(21) << "\n";

    // std::cout << helper(1);           // ERROR: helper was never exported
    return 0;
}

Output:

49 27
18 42

Three more pieces cover almost everything else.

The global module fragment, for including old headers:

module;                                  // global module fragment starts here
#include <string>
#include <cmath>
export module report;                    // the module declaration comes after

export std::string title() { return "Report"; }

Nothing in the global module fragment is exported — the headers are there for the module's own use.

An implementation unit, so the interface stays small:

// ---------- report.cppm : interface ----------
module;
#include <string>
export module report;

export std::string title();              // declared here
export std::string body();

// ---------- report.cpp : implementation ----------
module;
#include <string>
#include <sstream>
module report;                           // no 'export' -- this is an implementation unit

std::string title() { return "Report"; }         // defined here
std::string body()  { return "..."; }

An implementation unit automatically sees everything in its own module's interface, with no import needed.

Partitions, for splitting a large module without splitting its name:

export module shop:cart;                 // an interface partition
export struct Cart { int items = 0; };

export module shop;                      // the primary interface unit
export import :cart;                     // re-export the partition to consumers
export import :orders;

Consumers still write import shop;. Partitions are internal structure — import shop:cart; from outside the module is not allowed.


Technical Depth: What Modules Actually Fix

The problem with #include

#include is a preprocessor directive, not a language feature. It performs textual substitution before the compiler proper sees anything:

#include <vector>       // ~20,000 lines of text, pasted in
#include <string>       // ~15,000 more
#include "engine.h"     // which includes 30 other headers

Every consequence below follows from "it is a paste":

  • Repeated work. A header included by 200 translation units is parsed 200 times. Template-heavy headers dominate build times in most large C++ projects.
  • Macro leakage. A header that does #define max(a,b) ... or #define ERROR 3 rewrites the code of everything downstream. Windows' min/max macros are the canonical example.
  • Order dependence. Because each paste happens in sequence, swapping two #include lines can change what compiles.
  • No encapsulation. Anything in the header is visible. Private helpers, implementation types and internal constants are all part of your surface by accident.
  • Include guards. Every header needs #pragma once or a guard macro, and forgetting one produces a redefinition error.
  • ODR fragility. Two headers defining the same entity slightly differently is ill-formed and often not diagnosed.

What a module does instead

The compiler reads the interface unit once and writes a BMI — a Built Module Interface, a binary file (.pcm, .ifc, .gcm depending on toolchain) holding the already-parsed, already-checked declarations. Every import loads that. The saving grows with the number of consumers.

Property#includeModule
Parsed per consumerYes, every timeNo, once
Macros cross the boundaryYesNo
Order of declarations mattersYesNo
Needs include guardsYesNo
Private helpers hiddenNoYes
Affected by the consumer's macrosYesNo
Build order constraintsNoneInterfaces must be built first

The macro point deserves emphasis because it cuts both ways. A module cannot leak a macro into you, and a consumer's macros cannot reach into the module — so a module compiles the same way no matter who imports it. The flip side is that a module cannot export a macro at all. A library whose API is macros must keep a header alongside.

Visibility versus reachability

Non-exported entities are invisible to importers, but they are still reachable — the compiler knows about them well enough to use them:

export module widgets;

struct Impl { int n; };                  // not exported
export struct Widget {
    Impl detail;                         // fine: consumers can hold a Widget
};
export Widget make();                    // fine: they can call this

A consumer can copy, store and destroy a Widget — all of which need Impl's layout — but cannot name Impl or declare a variable of that type. This is real encapsulation, not a naming convention. The same applies to non-exported operator== overloads, which remain findable by argument-dependent lookup for exported types.

If you want something to be truly private to the interface unit and invisible even to reachability, use the private module fragment:

export module widgets;
export void run();

module : private;                        // nothing below is reachable to importers
void run() { /* ... */ }

Changing anything below module : private; does not force consumers to recompile.

Build ordering is the new constraint

With headers, translation units are independent and can be compiled in any order. With modules, a consumer cannot compile until the BMI of everything it imports exists — so the build becomes a dependency graph that must be discovered before compiling. That is why module support depends as much on the build system as the compiler:

# Rough shape; the exact flags differ per toolchain.
# GCC:
g++ -std=c++20 -fmodules-ts -c mathutils.cppm
g++ -std=c++20 -fmodules-ts main.cpp mathutils.o -o app

# Clang:
clang++ -std=c++20 --precompile mathutils.cppm -o mathutils.pcm
clang++ -std=c++20 -fmodule-file=mathutils=mathutils.pcm main.cpp mathutils.pcm -o app

# MSVC:
cl /std:c++20 /interface /TP mathutils.ixx
cl /std:c++20 main.cpp mathutils.obj

In practice you delegate this. CMake 3.28 and later supports modules directly through a FILE_SET CXX_MODULES, scanning sources to build the dependency graph:

add_library(mathutils)
target_sources(mathutils
    PUBLIC FILE_SET CXX_MODULES FILES mathutils.cppm)
target_compile_features(mathutils PUBLIC cxx_std_20)

File extensions are conventions, not rules: MSVC prefers .ixx, Clang and CMake prefer .cppm, GCC accepts .cc/.cpp.

Migrating gradually

You do not have to convert a codebase at once. There are four levels, and mixing them is expected:

StepWhat it looks likeGain
1. Headers as they are#include "engine.h"None, but nothing breaks
2. Header unitsimport "engine.h"; or import <vector>;Parsed once, macros still exported
3. Wrap in a moduleGlobal module fragment + export declarationsEncapsulation, no macro leakage
4. Native moduleNo #include at all; import std; (C++23)Full benefit

A header unit (import <vector>;) is the useful halfway house: the header is compiled once into a BMI, but it keeps header semantics including macro export. C++23 adds import std;, which replaces the whole standard library include list with one line.

What does not change

  • Templates still need their definitions in the interface — but the interface is compiled once instead of per consumer, so the cost is paid once.
  • Linkage and extern "C" work as before; modules affect name visibility, not the ABI.
  • Circular dependencies are still forbidden, and now enforced: two modules cannot import each other, and partitions cannot form a cycle. Break the cycle with a third module or a partition both depend on.
  • One module can span many files, and one file cannot declare two modules.

Current state, honestly

Modules are the most substantial change to how C++ code is organised since templates, and support arrived unevenly: MSVC has been usable the longest, Clang and GCC have both become workable, and the ecosystem — package managers, static analysers, IDE indexers — is still catching up. For a new project on a recent toolchain with CMake 3.28+, they are a reasonable choice. For an existing codebase, start at step 2 of the table above and expect the build system to be the harder half of the work.


Real World Example: A Geometry Library as a Module

Five files. Two interface partitions hold the types and the maths, a primary interface unit stitches them together, an implementation unit keeps the formatting code out of the interface, and a consumer imports the whole thing with one line.

// ============ geometry-shapes.cppm : interface partition ============
module;
#include <string>
export module geometry:shapes;

export struct Rectangle { double width = 0, height = 0; };
export struct Circle    { double radius = 0; };

export std::string name(const Rectangle&) { return "rectangle"; }
export std::string name(const Circle&)    { return "circle"; }
// ============ geometry-measure.cppm : interface partition ============
export module geometry:measure;
import :shapes;

// Not exported: usable inside the module, invisible to importers.
constexpr double kPi = 3.14159265358979;

export constexpr double area(const Rectangle& r) { return r.width * r.height; }
export constexpr double area(const Circle& c)    { return kPi * c.radius * c.radius; }

export constexpr double perimeter(const Rectangle& r) { return 2 * (r.width + r.height); }
export constexpr double perimeter(const Circle& c)    { return 2 * kPi * c.radius; }
// ============ geometry.cppm : primary interface unit ============
module;
#include <string>
export module geometry;

export import :shapes;                   // re-export both partitions
export import :measure;

export std::string report(const Rectangle& r);   // declared, not defined
export std::string report(const Circle& c);
// ============ geometry.cpp : implementation unit ============
module;
#include <string>
#include <sstream>
#include <iomanip>
module geometry;                         // no 'export': implementation only

namespace {
    std::string twoPlaces(double v) {
        std::ostringstream out;
        out << std::fixed << std::setprecision(2) << v;
        return out.str();
    }
}

std::string report(const Rectangle& r) {
    return name(r) + ": area " + twoPlaces(area(r))
                   + ", perimeter " + twoPlaces(perimeter(r));
}

std::string report(const Circle& c) {
    return name(c) + ": area " + twoPlaces(area(c))
                   + ", perimeter " + twoPlaces(perimeter(c));
}
// ============ main.cpp : consumer ============
#include <iostream>
import geometry;

int main() {
    constexpr Rectangle wall{4.0, 2.5};
    constexpr Circle window{0.75};

    static_assert(area(wall) == 10.0);            // constexpr survives the module boundary

    std::cout << report(wall) << "\n";
    std::cout << report(window) << "\n";

    // std::cout << kPi;              // ERROR: never exported
    // std::cout << twoPlaces(1.0);   // ERROR: internal to the implementation unit
    // import geometry:measure;       // ERROR: partitions are private to the module

    return 0;
}

Output:

rectangle: area 10.00, perimeter 13.00
circle: area 1.77, perimeter 4.71

A CMake build for this, on CMake 3.28 or later:

cmake_minimum_required(VERSION 3.28)
project(geometry_demo CXX)

add_library(geometry)
target_sources(geometry
    PUBLIC
        FILE_SET CXX_MODULES FILES
            geometry-shapes.cppm
            geometry-measure.cppm
            geometry.cppm
    PRIVATE
        geometry.cpp)
target_compile_features(geometry PUBLIC cxx_std_20)

add_executable(app main.cpp)
target_link_libraries(app PRIVATE geometry)

Notice what main.cpp does not contain. There is no include path, no header guard, no list of five headers in a particular order, and no way to accidentally depend on an implementation detail. import geometry; is the entire dependency, and it is a name rather than a file path — the build system maps the name to a BMI, so moving geometry-measure.cppm into a subdirectory changes nothing in any consumer.

The three commented-out lines in main are each a compile error for a different reason, and together they are the whole encapsulation story. kPi is declared in an interface partition but not exported, so it is usable by area and invisible to importers — the thing a header physically cannot do. twoPlaces sits in an anonymous namespace inside the implementation unit, so it is invisible even to the rest of the module. And import geometry:measure; fails because partitions are internal structure: the library author can reorganise them freely without breaking a single consumer, which is exactly the freedom that splitting a header into engine_detail.h never gives you.

The static_assert(area(wall) == 10.0) in the consumer is a small but pointed detail. area is constexpr, and constexpr works across the module boundary, so the compiler evaluates a function defined in another module unit at compile time. Modules do not weaken anything about the language — inlining, constant evaluation and template instantiation all still work; the change is only in how declarations reach the consumer.

The split between geometry.cppm and geometry.cpp is the modules answer to header/source separation, and it is a genuine improvement. report is declared in the interface and defined in the implementation unit, so <sstream> and <iomanip> — a substantial amount of template-heavy text — are never seen by anything that imports geometry. With headers, either those includes go in the header and everyone pays for them, or you hide them behind a forward declaration and a separate .cpp and accept that the header is now lying about what the type needs. Editing twoPlaces also does not force consumers to rebuild, because nothing in the interface changed.

Finally, the ordering constraint is visible in the CMake file, even though nothing in it states an order. geometry-shapes.cppm must be compiled before geometry-measure.cppm (which imports it), and both before geometry.cppm. CMake scans the sources, discovers the import lines, and builds the graph itself. That scanning step is precisely what older build systems cannot do, and why "does my toolchain support modules" is really a question about the build system.


Common Mistakes

  1. Putting #include after the module declaration. Includes belong in the global module fragment, which starts with a bare module; line before export module name;.
  2. Expecting macros to be exported. They are not, by design. A macro-based API needs a header alongside the module.
  3. Forgetting export. A declaration without it is invisible to importers, and the error appears in the consumer, not the module.
  4. importing a partition from outside its module. import geometry:measure; is only legal inside module geometry. Consumers import the whole module.
  5. Omitting export on import :partition. Plain import :cart; in the primary interface unit makes the partition available to the module but not to consumers; export import :cart; re-exports it.
  6. Creating a cycle. Two modules importing each other will not build. Extract the shared part into a third module.
  7. Mixing #include <string> and import std; in the same translation unit. Legal in principle, a source of duplicate-declaration pain in practice. Pick one per file.
  8. Assuming the file extension matters. It is a toolchain convention; what makes a file a module unit is the export module or module declaration inside it.
  9. Building with a build system that does not scan for imports. Compiling in the wrong order fails with a missing-BMI error that looks nothing like a dependency problem.

Best Practices

  • Put #includes of legacy headers in the global module fragment, and export nothing from them.
  • Export the minimum. Everything you leave unexported is a detail you can change later without breaking consumers.
  • Keep declarations in the interface unit and definitions in an implementation unit, so heavy includes never reach importers.
  • Use partitions to organise a large module, and export import :part; to publish the ones consumers need.
  • Use module : private; for interface-unit definitions you want consumers never to be recompiled for.
  • Use CMake 3.28+ with FILE_SET CXX_MODULES rather than hand-written compiler invocations.
  • Migrate in steps: headers, then header units, then modules that wrap headers, then native modules.
  • Keep a header wrapper if your library must offer macros or support pre-C++20 consumers.
  • Check your whole toolchain — compiler, build system, and the analysers and IDEs your team relies on — before committing a codebase to modules.

Practice Exercises

  1. Convert a small two-header library of your own into a module. Keep the public functions exported, move every helper out of the exported set, and then deliberately try to use one of those helpers from main.cpp to see the error. Build it twice — once with hand-written compiler commands, once with CMake 3.28's FILE_SET CXX_MODULES — and note which parts of the ordering CMake worked out for you.
  2. Take the geometry module above and add a geometry:transform partition with scaled(const Rectangle&, double) and scaled(const Circle&, double). Export it from the primary interface unit, then answer three questions with a compile attempt for each: can a consumer import geometry:transform; directly, can transform use kPi from the measure partition, and what happens if transform imports measure while measure imports transform?
  3. Migrate a header that leans on the preprocessor. Start from a config.h that defines CONFIG_MAX_RETRIES, a CONFIG_LOG(msg) function-style macro and an #ifdef CONFIG_DEBUG block, and turn it into a config module. Confirm by compile error that the module cannot export any of the three macros, then replace each one with something that does cross the boundary — a constexpr value, an inline function or a lambda, and a constexpr bool the caller branches on with if constexpr. Keep the old config.h as a shim that includes nothing and simply import config;, and note which callers still fail to compile and why.