How do I use C++20 modules instead of headers?

With the introduction of C++20, modules provide a modern alternative to traditional header files, enabling better encapsulation and faster compilation times. Instead of including headers, you define modules that can be imported by other translation units, thus promoting better code organization and reducing dependencies.

Basic Structure of a C++20 Module

Here’s a simple example of how to define and use a module in C++20:

// my_module.cppm export module my_module; export int add(int a, int b) { return a + b; } // main.cpp import my_module; #include int main() { std::cout << "Sum: " << add(5, 3) << std::endl; return 0; }

In this example, we define a module named my_module that contains a simple function add(). We can then import this module in our main program and use its functionality directly.


C++20 modules header files code organization modern C++