Skip to content
Tutorials Center
My learning

Topics

Lesson 143 of 171 ยท Modern C++ and Beyond

C++20 Modules

Learn C++20 modules - why headers are slow and leaky, export module and import, implementation units, partitions, import std in C++23, and how to build modules today.

For fifty years, C and C++ have shared code between files the same way: #include pastes the text of a header into your source file, and the compiler reads all of it, every time, in every file that includes it. A simple program that includes <iostream> asks the compiler to process tens of thousands of lines it didn't write. Macros from one header can silently change code in another. Include order matters. Big projects spend most of their build time re-reading the same headers.

Modules, added in C++20, replace that copy-and-paste model with real, compiled interfaces. A module says explicitly what it exports; importers see exactly that and nothing else, macros don't leak in or out, and the compiler processes each module once and reuses the result. C++23 went further with import std;, the entire standard library as a single module. This lesson explains the problems modules solve, the syntax for writing and using them, how to organize larger modules, and the honest state of compiler and build-system support. It builds on Header Files and Multiple Source Files and Namespaces.

Our online editor compiles one file at a time without module support, so the module code on this page is read-only. The runnable examples demonstrate the header problems that modules fix and the same designs written in today's single-file style.

What's wrong with headers

#include is a preprocessor instruction: before the compiler proper sees your code, the preprocessor replaces the #include line with the full text of the file. That's simple and flexible, and it causes four lasting problems:

  1. Slow builds. Every .cpp file that includes <vector>, <string> and <map> makes the compiler parse and analyze them again from scratch. With 500 source files, the same standard headers are compiled 500 times.
  2. Leaking macros. A #define in any header affects all code after the include, including other libraries' headers. The infamous example is a system header that defines min and max as macros, breaking std::min.
  3. Order dependence. A header may only compile if something else was included first, or behave differently depending on which macros were defined before it.
  4. No real encapsulation. Everything in a header is visible to the includer, including helper functions and implementation details that you'd rather keep private. Conventions such as a detail namespace are all you have.

The second problem is the sneakiest, because it often produces no error at all:

C++ A macro leaking out of a header

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The macro version prints 3, not 6: textual substitution turned min(x, y) * 2 into x < y ? x : y * 2, and the * 2 ended up in the wrong branch. Any file that included the header gets this behavior, whether it wanted the macro or not. A module can't do this to you, because macros defined inside a named module are never visible to importers.

Headers also need include guards (or #pragma once), because pasting the same file twice would define everything twice. You can watch the guard work by pasting a "header" twice by hand, which is exactly what happens when two headers both include it:

C++ Textual inclusion and include guards

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

It compiles because the second copy is skipped. Delete the #ifndef/#define/#endif lines from both copies and you get "redefinition of 'struct Point'". Modules don't need guards: importing a module twice is simply a no-op.

Your first module

A module is defined by a module interface unit: a source file that starts with export module name;. Everything marked export is the module's public interface; everything else stays private to the module. File extensions aren't standardized: MSVC uses .ixx, Clang documentation uses .cppm, and GCC accepts any extension.

C++
// geometry.cppm: the module interface unit
export module geometry;          // this file defines the module "geometry"

import std;                      // modules can import other modules

namespace geometry {

// Not exported: visible only inside this module.
double square(double x) { return x * x; }

export struct Point {
    double x = 0;
    double y = 0;
};

export double distance(Point a, Point b) {
    return std::sqrt(square(a.x - b.x) + square(a.y - b.y));
}

export constexpr double pi = 3.141592653589793;

}  // namespace geometry
C++
// main.cpp: an importer
import geometry;
import std;

int main() {
    geometry::Point a{0, 0}, b{3, 4};
    std::println("distance: {}", geometry::distance(a, b));   // OK: exported
    // geometry::square(2.0);  // error: 'square' is not exported from the module
}

Things to notice:

  • Modules and namespaces are independent. export module geometry; doesn't create a namespace; you still write namespace geometry yourself. A module can export names in any namespaces, and a namespace can span several modules. Using a matching namespace is the common convention.
  • import is not #include. It's a declaration that ends with a semicolon and loads the compiled interface. The order of imports doesn't matter, and nothing from your file can affect what the module means.
  • Non-exported names have module linkage: other files in the same module can use them, but importers can't even name them. That's real encapsulation, enforced by the compiler.
  • You can export a whole block (export { ... }) or a whole namespace (export namespace geometry { ... }).

The same design in today's single-file style looks like this, with a detail namespace standing in for the module's private part. Compare which names an importer could reach:

C++ The geometry module as a namespace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last line works here, because a header's detail namespace is visible to everyone. In the module version, square isn't exported, so that line would be a compile error.

Exported, visible and reachable

One subtle rule: if an exported function returns a type that isn't exported, importers can still use the returned object (call its members, pass it along, bind it to auto), they just can't name the type. The standard calls this reachable but not visible:

C++
export module shop;

struct Receipt {                         // not exported
    double total;
    double tax() const { return total * 0.2; }
};

export Receipt checkout(double amount) { return {amount}; }

// importer:
auto r = shop::checkout(50.0);           // OK, type deduced
double t = r.tax();                      // OK, members are reachable
// Receipt r2{10.0};                     // error: Receipt is not visible

Splitting a module across files

Large modules spread over several files, just as a library spreads over several .cpp files today.

Implementation units hold definitions that importers don't need to see. They start with module name; (no export), automatically see everything declared in the interface, and changing them doesn't force importers to recompile:

C++
// geometry.cppm: interface: declarations only
export module geometry;

export namespace geometry {
    struct Point { double x = 0, y = 0; };
    double distance(Point a, Point b);
}
C++
// geometry.cpp: implementation unit
module geometry;                         // no export: implements the module
import std;

namespace geometry {
    double distance(Point a, Point b) { return std::hypot(a.x - b.x, a.y - b.y); }
}

Partitions split the interface itself into pieces, named module:partition. A partition is part of the same module, not a separate one; the primary interface re-exports the pieces it wants to publish:

C++
// geometry-shapes.cppm
export module geometry:shapes;           // a partition of geometry
export namespace geometry {
    struct Circle { double radius; };
    double area(Circle c);
}

// geometry-transforms.cppm
export module geometry:transforms;
export namespace geometry {
    struct Offset { double dx, dy; };
}

// geometry.cppm: the primary module interface
export module geometry;
export import :shapes;                   // re-export the partitions
export import :transforms;

Importers still write just import geometry;. Partitions are invisible from outside, and only the primary interface unit can be imported.

Two more pieces of syntax you'll meet in real code:

  • The global module fragment lets a module use old-style headers and macros internally. It goes before the module declaration, and anything it includes is not exported:

    C++
    module;                                // start of the global module fragment
    #include <sys/stat.h>                  // a C header with macros we need inside
    #define USE_FAST_PATH 1
    export module files;                   // the module itself starts here
    
  • export import re-exports another module, like a convenience header that bundles others: export import geometry; in a module named graphics means import graphics; gives you geometry too.

import std; (C++23)

C++23 standardized two modules for the standard library:

  • import std; gives you everything in namespace std: containers, algorithms, std::println, std::format, threads, and so on. It does not export macros, so things like assert, INT_MAX or errno still need their headers (<cassert>, <climits>, <cerrno>).
  • import std.compat; also provides the C library names in the global namespace (::printf, ::sqrt), for code that uses them without std::.
C++
import std;

int main() {
    std::vector<int> data{5, 3, 8};
    std::ranges::sort(data);
    std::println("{}", data);            // no #include lines at all
}

Importing the whole standard library sounds expensive, but it's the opposite: the module is compiled once, and importing it is typically faster than including even a single header like <iostream>, because the compiler loads a prebuilt binary representation instead of parsing text.

The standard also allows header units: import <vector>; treats a header as if it were a module, a halfway step for code that can't migrate yet. Support for header units is the weakest part of the module story in today's compilers and build systems, so most projects skip them and go straight to named modules plus import std;.

Building modules

Here's the catch that slowed adoption: with headers, any .cpp file can be compiled in any order. With modules, a module must be compiled before the files that import it, because importers read its compiled interface. The build system has to scan every source file, discover which module each file defines and imports, and order the compilation accordingly. That needed new compiler features (dependency scanning in a standard JSON format) and new build-system support.

Compiling by hand shows the order. With GCC 15:

Terminal
# Build the std module once (GCC 15 ships its source as bits/std.cc)
g++ -std=c++23 -fmodules -fsearch-include-path -c bits/std.cc

# Then the module interface, then the importer, then link
g++ -std=c++23 -fmodules -c geometry.cppm
g++ -std=c++23 -fmodules -c main.cpp
g++ geometry.o main.o -o app

GCC stores compiled interfaces in a gcm.cache directory. Clang produces .pcm files (--precompile), and MSVC produces .ifc files, with Visual Studio handling the details for you. The compiled interface files are not portable: they're tied to the exact compiler version and flags, so you ship module source files, never their binary interfaces.

In practice you let CMake do it. Since CMake 3.28, modules are listed in a CXX_MODULES file set, and CMake runs the dependency scan for you (with the Ninja or Visual Studio generators; the Makefile generator doesn't support modules):

CMAKE
cmake_minimum_required(VERSION 3.28)
project(shapes LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 23)

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

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

import std; support in CMake arrived later and is still marked experimental in many versions (CMAKE_CXX_MODULE_STD). The next lesson, Build Systems: Make and CMake, covers CMake itself.

Where things stand

  • MSVC has had the most complete module support for years, including import std; since Visual Studio 2022 17.5.
  • Clang supports named modules well since version 16 to 17, and import std; with libc++ since about version 18 to 19.
  • GCC gained solid named-module support in GCC 14 to 15, and import std; in GCC 15.
  • Build systems: CMake (3.28+ with Ninja) and MSBuild work; build2 and xmake support modules too. Many other tools lag behind.
  • IDEs and tools (code completion, clang-tidy, static analyzers) are still catching up, which is often the deciding factor for teams.

A practical migration path: new projects with a modern toolchain can use named modules for their own code and import std; for the library. Existing projects usually keep headers and convert one library at a time, often shipping both a header and a module wrapper (export module mylib; export import ...; or export using ...; declarations) during the transition. When a translation unit uses both, put all #include lines before all import declarations: mixing the two is legal, but it's where compilers have historically had the most bugs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A module's interface defines #define LIMIT 100 and exports a function. A file does import that_module;. Can it use LIMIT?

    Named modules don't export macros at all, which is one of their main benefits. If importers need a constant, export a constexpr variable instead.
  2. 2. In a module interface, double helper(double) is declared without export. What can an importer do with it?

    Non-exported names have module linkage. They're usable inside the module (including implementation units and partitions), but importers can't see them.
  3. 3. What does export module geometry; create?

    Modules and namespaces are independent features. The convention is to put the module's exports in a namespace of the same name, but you write that namespace yourself.
  4. 4. Why do modules need build-system support that headers didn't?

    Importers read the module's compiled interface. The build system scans sources to find which file provides and requires which module, then compiles them in dependency order.
  5. 5. Which statement about import std; is true?

    import std; exports declarations, not macros. Loading the prebuilt module is typically faster than parsing even one big header. The global C names come from import std.compat;.

Summary

  • #include pastes text: builds re-parse the same headers repeatedly, macros leak, include order matters and nothing is truly private.
  • A module interface unit starts with export module name;; only exported declarations are visible to importers, and macros never cross the boundary.
  • import name; loads a compiled interface; order doesn't matter and no include guards are needed. Modules and namespaces are independent.
  • Implementation units (module name;) hold private definitions; partitions (module name:part;) split big interfaces; the global module fragment (module;) allows legacy headers inside.
  • import std; (C++23) imports the whole standard library quickly; import std.compat; adds the global C names.
  • Modules must be compiled before their importers, so they need build-system support: CMake 3.28+ with Ninja, MSBuild, and recent GCC, Clang and MSVC.

Next: Build Systems: Make and CMake, where you'll learn how real C++ projects with many files and libraries are compiled.