Since C++20, a new feature is available: modules.
We're all used to C++ header and source files. And we all know their pros and cons. Because I'm reviewing a new C++ alternative for them, I'll focus on the cons of header files:
- header files are sensitive to the order they are included, and are usually included multiple times in a project. (usual mitigation: a guard #IFNDEF / #ENDIF construct in each header file).
- changes usually require that a significant amount of the project needs recompilation
- header files don't know the C++ language. They are handled by the precompiler (before C++ analysis starts)
Modules address these 3.
- You don't include module headers in your code, but import modules. No matter how many times a module is imported, it's a single cost in the build phase. And the order of import in different source files does not matter.
- changes in a module (either interface or implementation) doesn't proliferate throughout the whole build
- modules are parsed by the compiler. They are fully aware (and can take full advantage) of the language and compiler.
Example project
The example is a simple module called matlib. It exports a function plus().
Example interface: matlib_interface.cpp
/* * matlib_interface.cpp * * Created on: 2 dec. 2024 * Author: jancu */ module; export module matlib; export namespace matlib { int plus(int a, int b); }
Example implementation: matlib_implementation.cpp
/* * matlib_implementation.cpp * * Created on: 2 dec. 2024 * Author: jancu */ module; module matlib; namespace matlib { int plus(int a, int b) { return a + b; } }
Example of a program that uses the module: matlib_client.cpp
/* * matlib_main.cpp * * Created on: 2 dec. 2024 * Author: jancu */ import matlib; int main() { matlib::plus(1, 2); return 0; }
Ready for production?
The language feature (and GCC's implementation) is currently a minimal viable product. It works, and starts offering the promised advantages. You enable them by flagging that you use C++20 or higher. And provide the -fmodules-ts flag.
What's holding me from using it in anger at the moment, is the limited IDE support (syntax highlighting, drill to declarations). And that it currently requires that the module files are compiled before the files that import the module. But it's interesting, and a preparation for more to come.