Using modules
This page covers using C++ module files to organize your code into multiple files. It assumes you are using a Chemeketa project template.
Add a new file to the project folder and name it something like
functions.cxx. You can add files by right-clicking the project folder in the file explorer and selecting "New File" or by using the command palette (Ctrl+P or Cmd+P) and typing the new file name.Open up your
.cxxfile and add this to declare some functions and provide their definitions:module; // module implementation file must start with 'module;' // Include any standard headers here #include <string> export module functions; // Exported module interface // The name of your module should match your file name using namespace std; // OK to use in module implementation files /** @brief Example function declaration * @return the number 42 */ // Note the 'export' keyword before the function definition // That is needed to make the function available outside the module export int getAnswer() { return 42; } /** @brief Function that returns a greeting * @return "Hello, World!" */ export string getGreeting() { return "Hello, World!"; }To use your functions in
main.cpp, we must import the module to get the function declarations:#include <iostream> import functions; // Import your module using namespace std; int main() { cout << getGreeting() << endl; cout << "The answer is " << getAnswer() << endl; }Open a terminal window and do this to compile the program manually:
g++ -std=c++20 -fmodules-ts functions.cxx main.cpp -o program.exeThat should work. Note that the order of the source files now matters. We need to compile the module file first. Then run it with:
./program.exeTo make sure the new
.cxxfile is included when you build the program using VSCode, open up theMakefileand find the line that starts withSHARED_FILES. Add your new.cxxfile to that line so it looks like:SHARED_FILES = functions.cxxIf you look further down in the
Makefile, you will see thatSHARED_FILESis included when compiling both the main program and the unit tests.Now build and run the program using VSCode's Run and Debug feature. It should work correctly.
To use the functions in your
tests.cpp, we need to import the module there as well. Remove the existing sample functions and test code fromtests.cpp(leave the part that sets up doctest).Then add this below the doctest setup code:
import functions; // Import your module TEST_CASE( "test setup" ) { CHECK( getAnswer() == 42 ); CHECK( getGreeting() == "Hello, World!" ); }Build and run the tests using VSCode's Run and Debug feature to confirm that program also works. To compile the tests manually, do this in the terminal:
g++ -std=c++20 -fmodules-ts functions.cxx tests.cpp -o tests.exeThen run the tests with:
./tests.exe