Module Basics

Modules are mechanisms for including code from other files while encapsulating the implementation details. Like static libraries, modules are compiled separately and linked into the application. This differs from headers, which are included directly into the source code, akin to a large cut-and-paste operation.

The impact on compilation time can be significant, as modules are compiled only once, while headers are compiled with each translation unit that includes them. Large header-based libraries, such as <fmt>, <regex>, or <print>, can significantly increase compilation time even for simple builds. Using modules can lead to a dramatic improvement in compile times.

Module Units

A module has multiple components: at least one primary Module Interface Unit (MIU) and zero or more Module Implementation Units. All of these are C++ translation units, i.e., source files.

Module Interface Unit

A Module Interface Unit provides the module’s user-facing interface. It exports the declarations for the variables, functions, or classes available from the module. It may also provide implementation definitions, but this is not recommended except for trivial modules.

There are two types of MIUs:

  • Primary Module Interface Unit
  • Module Partition Interface Unit

There can only be one primary MIU for a module, but there may be multiple Module Partition Interface Units. Each MIU generates a Built (or Binary) Module Interface (BMI), which contains information about the module or the partition. The BMI is used to quickly provide the declaration information to the translation units using the module. The BMI isolates the code using the module from the module’s implementation by delivering only the declarations. Application code only needs recompilation when the MIU, specifically the BMI, changes.

Module Implementation Unit

As the name implies, a Module Implementation Unit contains the source code defining the interface declared in the MIU. It may also provide code for other implementation units in the module. As with MIUs, there are two types of implementation units, which will be discussed in detail later.

  • Module Implementation Unit
  • Internal Module Partition Unit

These, along with their MIU counterparts, encapsulate the module’s internals.