Module partitions and submodules are two techniques in C++20 that help organize and manage code within modules. They serve different purposes and have distinct characteristics.
Module partitions allow you to split a single module into multiple parts, which helps in managing large modules.
Partitions are internal to the module and are used to organize the implementation details. Here’s an example:
// Math.cppm
export module Math;
export import :Algebra;
export import :Geometry;
export int add(int a, int b);
// Math:Algebra.cppm
module Math:Algebra;
export int multiply(int a, int b) {
return a * b;
}
// Math:Geometry.cppm
module Math:Geometry;
export double calculateCircleArea(double radius) {
return 3.14 * radius * radius;
}
import :partitionName
syntax within the module.Submodules, on the other hand, are independent modules that can form a hierarchy.
They allow you to create modular and reusable code components that can be imported separately or as a group. Here’s an example:
// Math.Algebra.cppm
export module Math.Algebra;
export int multiply(int a, int b) {
return a * b;
}
// Math.Geometry.cppm
export module Math.Geometry;
export double calculateCircleArea(double radius) {
return 3.14 * radius * radius;
}
// Math.cppm
export module Math;
export import Math.Algebra;
export import Math.Geometry;
import moduleName.submoduleName
syntax.:partitionName
syntax and are internal, while submodules use the moduleName.submoduleName
syntax and are external.Module partitions and submodules are both useful tools in C++20 for organizing code within modules. Partitions help manage the internal structure of a module, while submodules create a hierarchy of independent modules that can be imported separately or together.
Answers to questions are automatically generated and may not have been reviewed.
A detailed overview of C++20 modules - the modern alternative to #include
directives. We cover import
and export
statements, partitions, submodules, how to integrate modules with legacy code, and more.
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.
View Course