Top Qs
Timeline
Chat
Perspective
Modules (C++)
Modular translation unit in C++ From Wikipedia, the free encyclopedia
Remove ads
Modules in C++ are a feature added in C++20 implementing modular programming as a modern alternative to precompiled headers.[1] A module in C++ comprises a single translation unit.[2] 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.[1] A module, once compiled, is stored as a .pcm (precompiled module) file which acts very similar to a .pch (precompiled header) file.[3]
Modules most commonly have the extension .cppm (primarily common within Clang and GCC toolchains), though some alternative extensions include .ixx and .mxx (more common in Microsoft/MSVC toolchains).[4]
Though the standard C language does not have modules, dialects of C allow for modules, such as Clang C.[5] However, the syntax and semantics of Clang C modules differ from C++ modules significantly.
Remove ads
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[6], but did not have the same laws of encapsulation as modules. Modules were first proposed in 2012 for inclusion to C++14[7], but underwent extensive revisions and an entire redesign until the modern form was merged into C++20.[8]
Remove ads
Main uses
Summarize
Perspective
Modules provide the benefits of precompiled headers of faster compilation than #include
d traditional headers, as well as and faster processing during the linking phase.[9][10] This is because modules are not handled by the C preprocessor during the preprocessing step, but rather directly by the compiler during compilation.[11] 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, although separation of "interface file" and "implementation file" is still possible with modules, though modules provide a cleaner encapsulation of code.[2] Modules eliminate the necessity of #include 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.[9] 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.[12]
A module is imported using the keyword import
followed by a module name[a], 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.[13] Modules can export named symbols, but not macros which are consumed before compilation.[14]
Unlike header inclusions, the order of import statements do not matter.[9] 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.[1] Modules do not enforce any notion of namespaces, but it is not uncommon to see projects manually associate modules to namespaces (for example, a namespace like exampleproj::util::contents
being tied to the module exampleproj.util.contents
).[1] 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.
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 (using import std;
).[15] The C++ standards offer two standard library modules:
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.[16] However, most compilers provide a flag to bypass or suppress that warning (for example -Wno-reserved-module-identifier
in Clang and GCC).[3]
Tooling support
Currently, only GCC, Clang, and MSVC offer support for modules and import std;
.[17] 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.[18]
Example
A simple example of using modules is as follows:
MyClass.cppm
export module myproject.MyClass;
import std;
export namespace myproject {
class MyClass {
private:
int x;
std::string name;
public:
MyClass(int x, const std::string& name):
x{x}, name{name} {}
[[nodiscard]]
int getX() const noexcept {
return x;
}
void setX(int newX) noexcept {
x = newX;
};
[[nodiscard]]
std::string getName() const noexcept {
return name;
}
void setName(const std::string& newName) noexcept {
name = newName;
}
};
}
Main.cpp
import std;
import myproject.MyClass;
using myproject::MyClass;
int main(int argc, char* argv[]) {
MyClass me(10, "MyName");
me.setX(15);
std::println("Hello, {0}! {0} contains value {1}.", me.getName(), me.getX());
}
Remove ads
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.[19][20] 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[11], 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.[9] 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 <string>;
to import the <string>
header, or import "MyHeader.h";
to import the file "MyHeader.h"
as a header unit.[1] Most build systems, such as CMake, do not support this feature yet.[21]
Anatomy
Summarize
Perspective
Module partitions and hierarchy
Modules may have partitions, which separate the implementation of the module across several files.[1] 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.[1]
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
(say A:C
), which implicitly resolves :B
to A:B
, because the module is named A
.[3] 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.[1]
Other than partitions, modules do not have a hierarchical system or "submodules", but typically use a hierarchical naming convention, similar to Java's packages[b]. Only alphanumeric characters and the period and underscore may appear in the name of a module.[22] In C++, the name of a module is not tied to the name of its file or the module's location, unlike in Java[23], and the package it belongs to must match the path it is located in.[24] For example, the modules A
and A.B
in theory are disjoint modules and need not necessarily have any relation, however such a naming scheme is often employed to suggest that the module A.B
is related or otherwise associated with the module A
.[1]
The naming scheme of a C++ module is inherently hierarchical, and the C++ standard recommends re-exporting "sub-modules" belonging to the same public API (i.e. module alpha.beta.gamma
should be re-exported by alpha.beta
, etc.), even though dots in module names do not enforce any hierarchy. The C++ standard recommends lower-case ASCII module names (without hyphens or underscores), even though there is technically no restriction in such names.[25] Also, because modules cannot be re-aliased or renamed (short of re-exporting all symbols in another module), module names can be prefixed with organisation/project names for both clarity and to prevent naming clashes (i.e. google.abseil
instead of abseil
).[25] Also, unlike Java, whose packages may typically include an additional top-level domain (TLD) in front to avoid namespace clashes, C++ modules need not have this convention (for example, it may be more common to see example.myfunctionality.MyModule
than com.example.myfunctionality.MyModule
, though both names are valid).
Module purview and global module fragment
In the above example, everything above the line export module myproject.MyClass;
in the file MyClass.cppm is referred to as what is "outside the module purview", meaning what is outside of the scope of the module.[1] Typically, all #include
s are placed outside the module purview between the statement module;
and the declaration of export module
, like so:
module; // Optional; marks the beginning of the global module fragment (mandatory if an include directive is invoked above the export module declaration)
// Headers are included in outside the module purview, before the module is declared
#include <print>
#include "MyHeader.h"
export module myproject.MyModule; // Mandatory; marks the beginning of the module preamble
// Imports of named modules and header units come after the module declaration
// Import statements are placed immediately after the module declaration and do not appear after any code or symbol declarations
// In non-module translation units, #include directives precede import statements
import std;
import <string>;
import myproject.util.UtilitySymbols;
import "Foo.h";
import <thirdlib/features/Feature.h>;
// Code here...
module: private; // Optional; marks the beginning of the private module fragment
All code which does not belong to any module exists in the so-called "unnamed module" (also known as the global module fragment), and thus cannot be imported by any module.[1]
The file containing main()
may declare a module, but typically it does not (as it is unusual to export main()
as it is typically only used as an entry point to the program, and thus the file is usually a .cpp
file and not a .cppm
file). A program is ill-formed if it exports main()
and doing so causes undefined behaviour[26], but will not necessarily be rejected by the compiler.
Private module fragment
A module may declare a "private module fragment" by writing module: private;
, in which all declarations or definitions after the line are visible only from within the file and cannot be accessed by translation units that import that module.[3] Any module unit that contains a private module fragment must be the only module unit of its module.[1]
Remove ads
Third-party library support
As modules are a recent addition and compiler vendors were notably slow to develop module support, most third-party libraries are still offered only as headers. However, some popular libraries have added module support. These include fmt
(a formatting and printing library), nlohmann.json
(a JSON library), and various boost.*
libraries from the Boost C++ libraries.[27]
Clang C modules
Summarize
Perspective
An unrelated, but similar feature are Clang C modules. Clang offers non-standard module support for C, however the semantics differ significantly from C++ modules. Clang C modules exist for essentially the same reason as C++ modules:[5]
- To ensure translation units are compiled only once
- To ensure translation units are included only once
- To prevent leakage of unwanted macros
- To ensure clear boundaries of a library (i.e. specify what headers belong to what library)
- To explicitly control what symbols are exported
C modules instead use a file called module.modulemap to define modules. For instance, the C standard library module map may look something like:
module std [system] [extern_c] {
module assert {
textual header "assert.h"
header "bits/assert-decls.h"
export *
}
module complex {
header "complex.h"
export *
}
module ctype {
header "ctype.h"
export *
}
module errno {
header "errno.h"
header "sys/errno.h"
export *
}
module fenv {
header "fenv.h"
export *
}
// ...more headers follow...
}
This allows for the importing of C libraries like so:
import std.io;
int main(int argc, char* argv[]) {
if (argc > 1) {
printf("Hello, %s!\n", argv[1]);
} else {
printf("Hello, world!\n");
}
return 0;
}
Clang C modules can also be used in C++, although this is less portable as these conflict with the existing module implementation in C++. For example, the std
module shown earlier can be extended to C++ using a requires
declaration:
module std {
// C standard library...
module vector {
requires cplusplus
header "vector"
}
module type_traits {
requires cplusplus11
header "type_traits"
}
// more headers...
}
Remove ads
See also
Notes
- The
import
keyword in C++ differs in meaning than other languages. For instance,import
in Java is actually analogous tousing
in C++ and not C++import
. In the former, an import simply aliases the type or de-qualifies a namespace, because Java loads .class files dynamically as necessary, thus making all types available simply by fully qualifying all namespaces (rather than having to explicitly declare accessible modules). However, in C++ modules are not automatically all linked, and thus they must be manually "imported" to be made accessible, asimport
indicates that the translation unit must access code in the imported module. Thus, it is probably more appropriate to compareimport
in C++ tomod
in Rust, which "declares" or indicates to the compiler to find the module to link against. - It is more appropriate to compare packages in Java and modules in C++, rather than modules in Java and modules in C++. Modules in C++ and Java differ in meaning. In Java, a module (which is handled by the Java Platform Module System) is used to group several packages together, while in C++ a module is a translation unit, strictly speaking.
Remove ads
References
Wikiwand - on
Seamless Wikipedia browsing. On steroids.
Remove ads