How do I use modules in C++20?

In C++20, modules are a new way to organize and encapsulate code for better modularity, faster compilation, and improved code reuse. Unlike traditional header files, which can lead to problems like include guard issues and circular dependencies, modules offer a more structured way to manage dependencies.

To use modules in C++20, you typically define a module with the `module` keyword, and you can use the `import` keyword to include other modules. Here is a simple example of how to define and use a module:

// math_module.cppm export module math_module; export int add(int a, int b) { return a + b; } export int subtract(int a, int b) { return a - b; } // main.cpp import math_module; #include int main() { std::cout << "Adding 5 and 3: " << add(5, 3) << std::endl; std::cout << "Subtracting 5 from 8: " << subtract(8, 5) << std::endl; return 0; }

C++20 modules programming software development code organization