Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. What headers get wrong
    4. A first module: export module and import
    5. Only exported names are visible
    6. Including headers: the global module fragment
    7. Splitting a module across files
    8. Implementation units
    9. Partitions
    10. Building modules with CMake
    11. Which one should I use?
    12. Under the hood
    13. Common pitfalls
    14. An implementation unit without its own includes
    15. A module interface outside a CXX_MODULES file set
    16. Try it yourself

    Module 8 · Organizing a project

    8.3Modules

    Replace pasted-in headers with modules: export what other files may use, import it by name, keep everything else private, and build it with CMake. Learn what works today and when headers are still the better choice.

    About 25 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. What headers get wrong
    4. A first module: export module and import
    5. Only exported names are visible
    6. Including headers: the global module fragment
    7. Splitting a module across files
    8. Implementation units
    9. Partitions
    10. Building modules with CMake
    11. Which one should I use?
    12. Under the hood
    13. Common pitfalls
    14. An implementation unit without its own includes
    15. A module interface outside a CXX_MODULES file set
    16. Try it yourself

    Key terms

    module
    A named, separately compiled piece of a program. It says which names it exports, and files that import it see only those.
    module interface unit (.cppm)
    The file that starts with export module name;. It says what the module exports.
    export
    Marks a declaration in a module interface as visible to files that import the module.
    import
    Makes a module's exported names available in this file, like import dna;.
    global module fragment
    The part of a module file between module; and the module declaration. It's where #include lines go.
    module implementation unit
    A source file that starts with module name; (no export). It defines what the interface declares; importers never see it.
    module partition
    One piece of a larger module, named name:part. Only files of the same module can import it.
    BMI (built module interface)
    The compiled form of a module interface that the compiler reads on import. GCC writes .gcm files, Clang writes .pcm files.

    Every #include pastes a header’s text into your file. So the compiler reads <string> again in every source file that includes it, a macro defined in a header changes the meaning of the code after it, and the order of your #include lines can matter. A module is compiled once into a form the compiler loads quickly, and a file that imports it sees only the names the module chose to export.

    In 30 seconds

    • export module dna; starts a module interface; export marks what other files may use.
    • import dna; uses it. Names that aren’t exported stay private, and macros never leak out.
    • #include lines go in the global module fragment: after module;, before export module dna;.
    • CMake builds modules from version 3.28 on, with Ninja, when you list them in a FILE_SET CXX_MODULES.

    What headers get wrong

    How a C++ program is built showed that #include copies a header’s text in, and Headers, source files and the one-definition rule built whole programs that way. Most C++ code is organized like that today, but it has costs:

    • The same headers are parsed again and again. With GCC’s standard library, #include <print> alone expands to tens of thousands of lines, read again for every source file that includes it.
    • Macros leak. A #define in a header applies to every line after the #include, in every file that includes it.
    • Order matters. A header can behave differently depending on what was included or defined before it.
    • One-definition-rule traps. A function defined in a header without inline breaks the link once two files include it.

    Here a header defines K as a macro for the k-mer length. main.cpp has its own parameter called K, and the preprocessor replaces it with 21:

    2 files, built together

    config.h
    #pragma once
    
    #define K 21
    main.cpp
    #include <print>
    
    #include "config.h"
    
    int kmer_count(int read_length, int K) {
        return read_length - K + 1;
    }
    
    int main() {
        std::println("{}", kmer_count(7, 3));
    }

    Build and run

    g++ -std=c++23 -Wall -Wextra -Wpedantic main.cpp -o app
    ./app

    The compiler rejects this

    In file included from main.cpp:3:
    config.h:3:11: error: expected ‘,’ or ‘...’ before numeric constant
        3 | #define K 21
          |           ^~
    main.cpp:5:37: note: in expansion of macro ‘K’
        5 | int kmer_count(int read_length, int K) {
          |                                     ^

    The error points into config.h, not at the code you wrote. Modules fix all four problems: a module is compiled once, its macros stay inside it, imports don’t depend on order, and a function defined in a module is compiled only there, so it can’t be defined twice.

    A first module: export module and import

    A module interface is a source file, by convention with the extension .cppm. Its first line names the module, and export in front of a declaration makes it visible to importers. import dna; in another file brings in what dna exports:

    3 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(app CXX)
    set(CMAKE_CXX_STANDARD 23)
    add_executable(app main.cpp)
    target_sources(app PRIVATE FILE_SET CXX_MODULES FILES dna.cppm)
    dna.cppm
    export module dna;
    
    bool is_gc(char base) {
        return base == 'G' || base == 'C';
    }
    
    export int hydrogen_bonds(char base) {
        return is_gc(base) ? 3 : 2;
    }
    main.cpp
    #include <print>
    
    import dna;
    
    int main() {
        std::println("{} {}", hydrogen_bonds('G'), hydrogen_bonds('A'));
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/app

    Output

    3 2
    • export module dna; says this file is the interface of the module dna. A module’s name doesn’t have to match its file name, though keeping them the same helps.
    • hydrogen_bonds is exported: a G–C base pair is held by three hydrogen bonds, an A–T pair by two. is_gc isn’t exported, so only code inside the module can call it.
    • import dna; ends with a semicolon, unlike #include. A file can mix both: main.cpp still includes <print>.
    • The FILE_SET CXX_MODULES line tells CMake that dna.cppm is a module interface; Building modules with CMake explains it.

    The module examples on this page are built without the sanitizers: GCC 15.2 has a bug that makes it crash on a module that includes headers when UndefinedBehaviorSanitizer is on. Compiler bugs like this are rare, but module support is newer than the rest of the compiler.

    Only exported names are visible

    Calling is_gc from main.cpp fails. To an importer, the name doesn’t exist:

    3 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(app CXX)
    set(CMAKE_CXX_STANDARD 23)
    add_executable(app main.cpp)
    target_sources(app PRIVATE FILE_SET CXX_MODULES FILES dna.cppm)
    dna.cppm
    export module dna;
    
    bool is_gc(char base) {
        return base == 'G' || base == 'C';
    }
    
    export int hydrogen_bonds(char base) {
        return is_gc(base) ? 3 : 2;
    }
    main.cpp
    #include <print>
    
    import dna;
    
    int main() {
        std::println("{}", is_gc('G'));
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/app

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:6:24: error: ‘is_gc’ was not declared in this scope
        6 |     std::println("{}", is_gc('G'));
          |                        ^~~~~

    To make it usable, put export in front of it. Whatever you leave unexported can change without breaking other files, so export only what callers need.

    An unexported type can still reach importers through an exported function: if make_read() is exported and returns an unexported Read, auto r = make_read(); works and r.sequence too. Only the name Read can’t be written outside the module.

    Key ideaPrivate by default

    Everything a header declares is visible to every file that includes it. In a module, nothing is visible until you export it, so a helper can’t clash with a name in another file, and no other file can come to depend on it.

    Including headers: the global module fragment

    Most modules need standard headers. They go in the global module fragment: start the file with module;, put the #include lines next, then export module dna;. Only preprocessor lines may appear in that part. Every #include belongs there: one after export module dna; would make the header’s declarations part of dna, and GCC then reports clashes deep inside the standard library.

    You can also export several declarations at once with an export { } block, or a whole namespace with export namespace:

    3 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(app CXX)
    set(CMAKE_CXX_STANDARD 23)
    add_executable(app main.cpp)
    target_sources(app PRIVATE FILE_SET CXX_MODULES FILES dna.cppm)
    dna.cppm
    module;
    
    #include <string>
    #include <string_view>
    
    export module dna;
    
    #define K 3
    
    export namespace dna {
    struct Read {
        std::string id;
        std::string sequence;
    };
    } // namespace dna
    
    export {
        std::string_view first_kmer(const dna::Read& read) {
            return std::string_view(read.sequence).substr(0, K);
        }
    
        int kmer_length() {
            return K;
        }
    }
    main.cpp
    #include <print>
    
    import dna;
    
    int main() {
        int K = 5;
        dna::Read read{"r1", "GATTACA"};
        std::println("{} {} {}", first_kmer(read), kmer_length(), K);
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/app

    Output

    GAT 3 5
    • The headers in the global module fragment don’t belong to dna: its <string> is the same <string> every other file sees.
    • #define K 3 works inside the module and stops at its end, so main.cpp can declare its own int K. A module never exports macros; to share a constant, export a constexpr variable.
    • export namespace dna { … } exports everything in the namespace. Importers write dna::Read, as with the namespaces in 8.1.

    Splitting a module across files

    Implementation units

    A big module can keep declarations in the interface and definitions in a module implementation unit: a .cpp file that starts with module dna;, without export. It sees everything the interface declares, exported or not. Importers never see it, so when only a function body there changes, files that import dna don’t need recompiling.

    This project also puts the module in a library, as CMake and libraries did with headers. The interface goes in the library’s CXX_MODULES file set; the implementation unit is an ordinary source:

    4 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(gc CXX)
    set(CMAKE_CXX_STANDARD 23)
    add_library(dna dna.cpp)
    target_sources(dna PUBLIC FILE_SET CXX_MODULES FILES dna.cppm)
    add_executable(gc main.cpp)
    target_link_libraries(gc PRIVATE dna)
    dna.cppm
    module;
    
    #include <string_view>
    
    export module dna;
    
    export int count_gc(std::string_view sequence);
    dna.cpp
    module;
    
    #include <string_view>
    
    module dna;
    
    int count_gc(std::string_view sequence) {
        int count = 0;
        for (char base : sequence) {
            count += base == 'G' || base == 'C';
        }
        return count;
    }
    main.cpp
    #include <print>
    
    import dna;
    
    int main() {
        std::println("{}", count_gc("GGCCAT"));
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/gc

    Output

    4

    dna.cpp includes <string_view> itself: the interface’s #include lines aren’t passed on to it. Common pitfalls shows what happens without it.

    Partitions

    A module partition splits the interface itself into several files. A partition’s name is the module’s name, a colon and a part name: a file dna-bases.cppm starting with export module dna:bases; is the bases part of dna. The main interface, dna.cppm, must pass on what the part exports with export import :bases;. A part that exports nothing, module dna:helpers;, holds code only the module’s own files use; they bring it in with import :helpers;. Every partition file goes in the CXX_MODULES file set. Importers still write import dna;; they can’t import a partition. Partitions are for modules big enough that one interface file gets hard to read; small modules don’t need them.

    Building modules with CMake

    A header can be compiled in any order, because the preprocessor reads it as text. A module can’t: before the compiler can build main.cpp, which says import dna;, it needs the BMI (built module interface) that compiling dna.cppm produces. So the build system must find out which file provides which module and build them in the right order. CMake does this, given:

    • cmake_minimum_required(VERSION 3.28) or later. Older versions build modules only behind experimental switches.
    • The Ninja generator (cmake -B build -G Ninja) or Visual Studio 2022. In CMake 4.2, the default “Unix Makefiles” generator stops with an error that it doesn’t support modules.
    • Module interfaces listed with target_sources(target PUBLIC FILE_SET CXX_MODULES FILES …). PUBLIC lets targets that link this one import them; a program, which nothing links to, uses PRIVATE. Implementation units and ordinary .cpp files are listed as usual.
    • A compiler that supports modules: GCC 14 or later, Clang 16 or later, or a recent Visual Studio.

    Modern C++import std; and header units

    C++23 adds import std;, which brings in the whole standard library as one module, faster than including even a few headers. Recent GCC, Clang and Visual Studio support it, but CMake (4.2, on this site) builds it only behind an experimental switch, so this course still includes standard headers. Header units (import <vector>;) turn an ordinary header into a module-like unit; CMake doesn’t build them yet. Support for both is still settling: check your compiler’s and CMake’s notes before you rely on them.

    Which one should I use?

    WhatWhenWhyHow
    HeadersCode that must build with older compilers or build systems, libraries you publish, anything that already works.Every compiler, build system and tool supports them.#include "dna.h", as in 8.1
    A moduleNew code in your own project, built with CMake 3.28+ and Ninja on a recent compiler.Faster rebuilds, private helpers, no leaking macros, no order effects.export module dna; in a .cppm, import dna; to use it
    Implementation unitsA module whose function bodies are long or change often.Importers don’t recompile when only a body changes.module dna; at the top of a .cpp
    import std;Once your compiler and build system support it without experimental switches.One import replaces every standard header, and it’s fast.import std;

    Rule of thumb: headers are still the safe default. Use modules for new code in a project whose compiler and build system you control, and keep standard headers in the global module fragment until import std; builds without extra switches.

    Under the hood

    When CMake builds a project with modules, each source file goes through three steps:

    1. Scan. CMake asks the compiler which module the file provides and which it imports. With GCC, that’s the -fdeps-format=p1689r5 flag in the build log, a format the compilers agreed on.
    2. Order. From the scan, CMake makes main.cpp wait for dna.cppm. Modules that import each other in a cycle are an error.
    3. Compile. Compiling dna.cppm produces an ordinary object file with the machine code, and the BMI (dna.gcm with GCC, dna.pcm with Clang), which describes what the module exports. Compiling main.cpp reads the BMI instead of parsing any text.

    The object file is linked like any other: the BMI only replaces the header’s role. It’s specific to the compiler, its version and the flags used, so libraries ship their .cppm source and each project builds its own BMI. Templates work as with headers: an exported function template is defined in the interface (or a partition), because importers instantiate it themselves, as Function templates explained.

    Common pitfalls

    An implementation unit without its own includes

    Without #include <string_view> in dna.cpp, GCC doesn’t know std::string_view there, so it reads count_gc as a variable, and its message is confusing:

    3 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(dna CXX)
    set(CMAKE_CXX_STANDARD 23)
    add_library(dna dna.cpp)
    target_sources(dna PUBLIC FILE_SET CXX_MODULES FILES dna.cppm)
    dna.cppm
    module;
    
    #include <string_view>
    
    export module dna;
    
    export int count_gc(std::string_view sequence);
    dna.cpp
    module dna;
    
    int count_gc(std::string_view sequence) {
        return static_cast<int>(sequence.size());
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/app

    The compiler rejects this

    dna.cpp:3:19: error: ‘int count_gc’ redeclared as different kind of entity
        3 | int count_gc(std::string_view sequence) {
          |                   ^~~~~~~~~~~
    In module dna, imported at dna.cpp:1:
    dna.cppm:7:12: note: previous declaration ‘int count_gc@dna(std::string_view)’
        7 | export int count_gc(std::string_view sequence);
          |            ^~~~~~~~
    compilation terminated due to -fmax-errors=1.

    Clang says what’s wrong: missing #include <string_view>. Give each implementation unit its own global module fragment with the headers it uses.

    A module interface outside a CXX_MODULES file set

    Listing dna.cppm with the ordinary sources compiles it, but CMake then finds a module nobody declared, and stops:

    2 files, built together

    CMakeLists.txt
    cmake_minimum_required(VERSION 3.28)
    project(dna CXX)
    set(CMAKE_CXX_STANDARD 23)
    add_library(dna dna.cppm)
    dna.cppm
    export module dna;
    
    export int square(int x) {
        return x * x;
    }

    Build and run

    cmake -B build -G Ninja
    cmake --build build
    ./build/app

    The compiler rejects this

    /usr/bin/cmake -E cmake_ninja_dyndep --tdi=CXXDependInfo.json --lang=CXX --modmapfmt=gcc --dd=CXX.dd @CXX.dd.rsp
    CMake Error: Output dna.cppm.o provides the `dna` module but it is not found in a `FILE_SET` of type `CXX_MODULES`

    Fix it with add_library(dna) and target_sources(dna PUBLIC FILE_SET CXX_MODULES FILES dna.cppm).

    Try it yourself

    Try it yourself

    A module can’t export macros, so before this code can move into module dna, its two macros must become things a module can export. Replace KMER_LENGTH with a constexpr variable (see constexpr) and KMER_COUNT with a function. The second line should then print 10, not 12.

    #include <print>
    
    #define KMER_LENGTH 3
    #define KMER_COUNT(n) n - KMER_LENGTH + 1
    
    int main() {
        int read_length = 7;
        std::println("{}", KMER_COUNT(read_length));
        std::println("{}", 2 * KMER_COUNT(read_length));
    }

    Expected output

    5
    10
    Show a hint

    A constexpr int variable replaces the constant. A function with an int parameter replaces KMER_COUNT; it computes its whole result before anything multiplies it.

    Show a solution
    #include <print>
    
    constexpr int kmer_length = 3;
    
    int kmer_count(int read_length) {
        return read_length - kmer_length + 1;
    }
    
    int main() {
        int read_length = 7;
        std::println("{}", kmer_count(read_length));
        std::println("{}", 2 * kmer_count(read_length));
    }

    A macro is text pasted in place, so 2 * KMER_COUNT(read_length) became 2 * read_length - 3 + 1, which is 12. A function returns a value, so 2 * kmer_count(read_length) is 2 * 5. In a module you can write export constexpr int kmer_length = 3; and export the function too; the macros could not be exported at all.

    Saved in this browser only.