Modules (C++)


Modules in C++ are a feature added in C++20 implementing modular programming as a modern alternative to precompiled headers. A module in C++ comprises a single translation unit. Like header files and implementation files, a module can contain declarations and definitions, but differ from precompiled headers in that they do not require the preprocessor directive #include, but rather are accessed using the word import. A module must be declared using the word module to indicate that the translation unit is a module. A module, once compiled, is stored as a file which acts very similar to a file. Module symbols and imports are resolved at the compilation stage, not the linking stage.
Modules most commonly have the extension , though some alternative extensions include and , or even the traditional C++ extension.
Though the standard C language does not have modules, dialects of C allow for modules, such as Clang C. However, the syntax and semantics of Clang C modules differ from C++ modules significantly.

History

Prior to the conception of modules, C++ relied on the system of headers and source files. Precompiled headers existed and were similar to modules as snapshots of translation units easier to parse by the compiler and thus providing faster compilation, but did not have the same laws of encapsulation as modules. Modules were first proposed in 2012 for inclusion to C++14, but underwent extensive revisions and an entire redesign until the modern form was merged into C++20. An attempt to implement the feature in 2018 using Fortran existed.

Main uses

Modules provide the benefits of precompiled headers with faster compilation than #included traditional headers, as well as faster processing during the linking phase. This is because modules are not handled by the C preprocessor during the preprocessing step, but rather directly by the compiler during compilation. Modules also reduce boilerplate by allowing code to be implemented in a single file, rather than being separated across a header file and source implementation. Separation of "interface file" and "implementation file" is still possible with modules, though modules provide a cleaner encapsulation of code. Separating code interface and source implementation, however, is necessary for benefiting from incremental builds. Modules eliminate the necessity of guards or pragma once|, as modules do not directly modify the source code. Modules, unlike headers, do not have to be processed or recompiled multiple times. However, similar to headers, any change in a module necessitates the recompilation of not only the module itself but also all its dependencies, and the dependencies of those dependencies, et cetera. Like headers, modules do not permit circular dependencies, and will not compile.
A module is imported using the keyword import followed by a module name, while a module is declared with export module followed by the name. All symbols within a module meant to be exposed publicly are marked export, and importing the module exposes all exported symbols to the translation unit. If a module is never imported, it will never be linked. Modules can export named symbols, but not macros which are consumed before compilation. Thus, modules prevent macros from unwantedly crossing translation units.
Unlike header inclusions, the order of import statements do not matter. A module can allow for transitive imports by marking an import with export import, which re-exports the imported module to a translation unit that imports the first module. Modules do not enforce any notion of namespaces, though by convention, modules should match namespaces and source file paths. using statements will only be applied in translation units if explicitly marked export, making it much less likely that using a using statement to bring symbols into the global namespace will cause name clashes across module translation units. This resolves pollution of using statements in headers, which due to textual inclusion of the header by an #include directive, will always result in using statements adding symbols into scope, even if unintentional.
The keyword export was first introduced in C++03 when "exported templates" were added to C++. These were later removed in C++11, due to very few compilers actually supporting the feature. The only compiler known to support exported templates was Comeau C/C++.

Standard library modules

Since C++23, the C++ standard library has been exported as a module as well, though as of currently it must be imported in its entirety. The C++ standards offer two standard library modules:
NameDescription
Exports all declarations in namespace std and global storage allocation and deallocation functions that are provided by the importable C++ library headers including C library facilities.
Exports the same declarations as the named module std, and additionally exports functions in global namespace in C library facilities. It thus contains "compat" in the name, meaning compatibility with C.

The module names std and std.* are reserved by the C++ standard, and thus declaring a module whose name matches either pattern will issue a compiler warning. However, most compilers provide a flag to bypass or suppress that warning.

Tooling support

Currently, only GCC, Clang, and MSVC offer support for modules and import std;. The Clangd language server supports modules.
Build system support varies. CMake, MSBuild, XMake, Meson, and Build2 provide full support for modules. Generated build systems such as Make and Ninja also have support for modules. However, Gradle for C++ and Bazel do not yet support modules. Qt moc does not recognise modules in its preprocessor currently.

Example

A simple example of using modules is as follows:

export module org.wikipedia.project.Person;

import std;

using std::string;
using std::string_view;

export namespace org::wikipedia::project


import std;
import org.wikipedia.project.Person;
using org::wikipedia::project::Person;
int main

Header units

Headers may also be imported using import, even if they are not declared as modules. Imported headers are called "header units", and are designed to allow existing codebases to migrate from headers to modules more gradually. The syntax is similar to including a header, with the difference being that #include is replaced with import. As import statements are not preprocessor directives but rather statements of the language read by the compiler, they must be terminated by a semicolon. Header units automatically export all symbols, and differ from proper modules in that they allow the emittance of macros, meaning all translation units that import the header unit will obtain its contained macros. This offers minimal breakage between migration to modules. The semantics of searching for the file depending on whether quotation marks or angle brackets are used apply here as well. For instance, one may write import ; to import the header, or import "MyHeader.h"; to import the file "MyHeader.h" as a header unit. Most build systems, such as CMake, have only experimental support for this.
Similar to Go import statements, header unit import statements are followed by a raw string literal representation of the path. However, one cannot write a compile-time string literal and import that expecting it to be interpreted as a path.

Anatomy

Module partitions and hierarchy

Modules may have partitions, which separate the implementation of the module across several files. Module partitions are declared using the syntax A:B, meaning the module A has the partition B. Module partitions cannot individually be imported outside of the module that owns the partition itself, meaning that any translation unit that requires code located in a module partition must import the entire module that owns the partition.
The module partition B is linked back to the owning module A with the statement import :B; in the file containing the declaration of module A or any other module partition of A, which implicitly resolves :B to A:B, because the module is named A. These import statements may themselves be exported by the owning module, even if the partition itself cannot be imported directly, and thus importing code from a partition is done by just importing the entire module.
If a module is split between module interface and module implementation, its translation unit consists of both the interface and implementation. Similarly, if a module has partitions, its translation unit encompasses all of those modules as well.
Other than partitions, modules do not have a hierarchical system or "submodules", but typically use a hierarchical naming convention, similar to Java's packages. Only alphanumeric characters, the underscore, and the period may appear in the name of a module. In C++, the name of a module is not tied to the name of its file or the module's location, unlike in Java, and the package it belongs to must match the path it is located in. For example, the modules A and A.B in theory are disjoint modules and need not necessarily have any relation, however employing such a naming scheme with periods in the module name is used to suggest that the module A.B is related or otherwise associated with the module A.
The naming scheme of a C++ module is intended to allow a hierarchy to be suggested, and the C++ standard recommends re-exporting "sub-modules" belonging to the same public API, even though dots in module names do not enforce any hierarchy. The C++ standard recommends lower-case ASCII module names, even though there is technically no restriction in such names. Also, because modules cannot be re-aliased or renamed, module names can be prefixed with organisation and project names for both clarity and to prevent naming clashes. Also, unlike Java, whose packages may typically include an additional top-level domain in front to avoid namespace clashes, C++ modules need not have this convention.
If symbols inside a namespace are exported, the namespace itself is implicitly exported, but only the symbols explicitly exported within it.

export module org.wikipedia.mymodule;
namespace org::wikipedia::mymodule

If a module exports a function whose return type or has as a parameter type a non-exported type, the module is ill-informed unless it is a pointer.

export module org.wikipedia.mymodule;
// non-exported type
class Hidden ;
export namespace org::wikipedia::mymodule

Client code cannot call methods, access data, or destroy the object. Furthermore, even using static reflection or run-time type information can the type be inspected.