⏲️ ~ 6 minutes Advanced
Modules offer a simpler, more efficient, and safer alternative to the traditional file inclusion system using the preprocessor.
Traditionally, code in C++ has been organized into header files .h
and implementation files .cpp
. But this has frankly always been a hassle inherited from C 🤷.
The introduction of modules in C++11 and their formalization in C++20 aims to completely change the way C++ projects are structured and managed.
The concept of a module exists in many languages and has become a standard in programming. It represents a huge improvement for C++.
What is a module?
In simple terms, a module in C++ is a unit of code that consists of a declaration and definition of functions, classes, all in the same file.
Key Features
- Encapsulation: Modules allow you to define what is accessible from the outside (what is exported) and what is private to the module (what is kept internal).
- Compilation Optimization: Modules allow for compiling once and reusing that result, reducing compilation times.
- Elimination of Circular Dependencies: Modules allow importing only the necessary components, avoiding unnecessary dependencies.
If you are a regular programmer, by now you should be crying tears of joy seeing all these advantages (I’m still crying 😭)
Basic Syntax of Modules
Declaring a Module
A module in C++ is declared using the keyword module
followed by the name of the module.
The declaration is generally placed in a separate file with the extension .cppm
(or sometimes .ixx, although .cppm is more common and standard in most compilers).
module mymodule; // We declare a module named "mymodule"export void foo() { // We export the function foo std::cout << "Hello from foo!" << std::endl;}export class MyClass { // We export a class MyClasspublic: void sayHello() { std::cout << "Hello from MyClass!" << std::endl; }};
In this example:
module mymodule;
declares the modulemymodule
.- Functions and classes prefixed with
export
become accessible from outside the module.
Importing a Module
To use a module in another file, we simply use the keyword import
, which replaces the traditional #include
.
import mymodule; // We import the module "mymodule"int main() { foo(); // We call the exported function from mymodule MyClass obj; obj.sayHello(); // We use the class exported from mymodule}
In this example,
- The file
main.cpp
imports the modulemymodule
and uses the entities that have been exported (the functionfoo
and the classMyClass
).
Example with and without modules
Let’s see the advantages of modules by doing a simple example with the traditional header system and with the new module system.
Example using headers
First, let’s look at the traditional option with implementation and header files. We would have,
This file includes the header and uses the function sum
.
#include <iostream>#include "sum.h"int main() { int result = sum(3, 4); std::cout << "The sum is: " << result << std::endl; return 0;}
This file contains the declaration of the function sum
.
#ifndef SUM_H#define SUM_Hint sum(int a, int b);#endif
This file defines the function sum
.
#include "sum.h"int sum(int a, int b) { return a + b;}
To compile this program, you would typically use a command like:
g++ main.cpp sum.cpp -o program
Example using modules
Now we implement the same example using modules. Instead of having a separate header file and implementation file, we create a single module file.
This file contains both the declaration and definition of the function sum
, and it is exported so that other files can use it.
export module sum;export int sum(int a, int b) { return a + b;}
To use the module, we simply import it in the main.cpp
file.
import sum;#include <iostream>int main() { int result = sum(3, 4); std::cout << "The sum is: " << result << std::endl; return 0;}
To compile the program with modules, the command would be something like:
g++ -fmodules-ts sum.cppm main.cpp -o program
The -fmodules-ts
option is used in some compilers like GCC to enable C++20 modules, although the options may vary depending on the compiler.
Benefits of Modules in C++
To a large extent, C++ modules are designed to replace the use of header files in the language.
Modules introduce a more modern, efficient, and safe way to organize and reuse code, addressing several problems associated with the traditional header system.
In case I haven’t convinced you yet, let’s look at some of their advantages 👇
Faster Compilation
- In the traditional system, each
.cpp
file must include all the necessary headers, which generates a lot of redundant processing. - Modules allow compiling units of code once and reusing them, significantly reducing compilation times.
Better Encapsulation
- Traditional header files expose both the interface (class, function declarations, etc.) and some implementation details to other files that include them.
- Modules clearly define which parts of the code are visible and accessible from other modules or files, facilitating better control over visibility and avoiding accidental dependencies.
Elimination of Redefinition Problems
- Headers often require the use of
#include guards
or#pragma once
to prevent multiple inclusions that cause redefinition errors. - Modules eliminate the need for these mechanisms, as their design automatically prevents multiple inclusions and redefinitions. 🎉🎉🎉
Avoidance of Unwanted Macros
- Macros in headers can create conflicts when included in different files and may unintentionally affect parts of the code.
- With modules, macros do not propagate outside the module in which they are defined.
Improvements in Readability and Maintenance
- Modules provide a more organized system that makes it easier to understand project dependencies, as each module explicitly defines its interfaces and does not rely on preprocessor directives like
#include
.