Insight 6.5.1.
You can think of a module as a .cpp file that (among other things) will automatically generate its own .h file
.h
to declare what is in the file. When we make use of the module in other files, the compiler automatically finds and reads that file to discover what is available.
module
keyword is used to declare that we are starting a module. Within a module, export
is used to state what code in the module is made available to use outside of the module. In a simple library, we may export everything. But in a more complex code base, there may be helper functions that are needed in the module that do not make sense to use outside of the module. In that case, we would not export
those functions.
.cxx
) we choose. But it is common to use something other than .cpp
to indicate that the file is a C++ module. .cxx
is one common extension used for this purpose.
library.cxx
// Start global module fragment
module;
// All includes go here
#include <cmath>
// Start module, declare its name and make available outside this module
export module library;
// Using namespace is safer in a module as it will be scoped to this module only
// The place to do so is after the module declaration
using namespace std;
// Declare the functions in the module. Only the functions marked with `export`
// will be available outside this module.
/**
* @brief Gets the number 2. A silly function that demonstrates a function
* that is NOT exported
*
* @return 2
*/
int getMultiplier() {
return 2;
}
/**
* @brief Doubles the value of the input number
* This function is exported for use outside this module.
*
* @param num an integer value
* @return int 2x the input number
*/
export int doubleValue(int num) {
int result = getMultiplier() * num;
return result;
}
module;
to declare that this is a module and begin the βglobal module fragmentβ. Any includes (uses of non-module libraries) need to be in this part of the file. If there are no includes needed in a file, this part can be skipped. (We could remove the <cmath
include and then remove everything before line 8.)library
export
makes library
available outside of the module.export
to state that the doubleValue
function will also be available outside of the module.main.cpp
(with module import)-fmodules-ts
flag to enable modules and ensure that the compiler is using C++20 (or above) features with -std=c++20
.
$ g++ -std=c++20 -fmodules-ts library.cxx main.cpp -o program.exe
mycode.cxx
for a library that just has a void function called print
that takes a string parameter. You will not use all of the blocks.