Namespaces & Modules
Namespaces
Namespaces are used to organize code and prevent naming conflicts. They allow you to group related code together and avoid naming clashes that might occur when different libraries or components are combined.
#include <iostream>
// First namespace named 'Math' containing a function named 'operation'
namespace Math {
int operation(int a, int b) {
return a + b;
}
}
// Second namespace named 'Utility' containing a function named 'operation'
namespace Utility {
int operation(int a, int b) {
return a * b;
}
}
int main() {
// Resolve the naming conflict by using namespaces
int sum = Math::operation(3, 4);
int product = Utility::operation(5, 2);
// Display the results
std::cout << "Sum: " << sum << std::endl;
std::cout << "Product: " << product << std::endl;
return 0;
}
Modules
Most C++ projects use multiple source files (or more precisely, the translation units), and so they need to share declarations and definitions across those units. The usage of headers is prominent for this purpose, an example being the standard library whose declarations can be provided by including the corresponding header.
C++20 introduces modules, a modern solution that turns C++ libraries and programs into components. A module is a set of source code files that are compiled independently of the source files. Modules eliminate or reduce many of the problems associated with the use of header files. They often reduce compilation times.
// Module interface file (module.h)
export module mymodule;
export int add(int a, int b);
// Module implementation file (module.cpp)
module mymodule;
int add(int a, int b) {
return a + b;
}
// main.cpp
import mymodule;
int main() {
int result = add(3, 4);
return 0;
}