Module Partitions vs Submodules
What are module partitions, and how do they differ from submodules?
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
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;
}
Characteristics of Module Partitions
- Internal Structure: Partitions are used to divide the internal structure of a single module.
- Visibility: Partitions are not visible outside the module. They are used to manage the implementation details within the module.
- Import Syntax: Partitions are imported using the
import :partitionName
syntax within the module.
Submodules
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;
Characteristics of Submodules
- Hierarchy: Submodules create a hierarchical structure, allowing for independent and reusable code components.
- Visibility: Submodules are visible outside the parent module and can be imported individually or as part of the parent module.
- Import Syntax: Submodules are imported using the
import moduleName.submoduleName
syntax.
Key Differences
- Purpose: Partitions are for organizing the internal structure of a single module, while submodules create a hierarchy of independent modules.
- Visibility: Partitions are not visible outside the module, whereas submodules are.
- Usage: Partitions use the
:partitionName
syntax and are internal, while submodules use themoduleName.submoduleName
syntax and are external.
Summary
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.
C++20 Modules
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.