Skip to main content

Section 6.6 Multiple Programs

Now that we know how to split code across multiple files, we can use that knowledge to build a project that has multiple programs. This is useful when we want to have one program that uses some code, and a separate program that tests the code.
In this section, we will look at a project that demonstrates building multiple different programs that all share some common code. Our code will be split into these files:
  • library.cxx: The library code we want to use and to test.
  • main.cpp: the main file for the β€œreal” program. It will have the main function. It will import library to help do its work.
  • tests.cpp: a test program that verifies the functions from library work correctly.

Note 6.6.1.

We are using a module, but we could replace library.cxx with library.h and library.cpp. The only necessary change would be to #include "library.h" instead of using import library;.
To compile the main program, we can use the same recipe as before:
$ g++ -std=c++20 -fmodules-ts library.cxx main.cpp -o program.exe
Note that we do not mention the tests.cpp file, as we do not want to build it into this program. We can’t build both main.cpp and tests.cpp into the same program. Each program can only have one main function. main.cpp defines one and the #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN line in tests.cpp forces that file to automatically create a main function in that file.
To compile the test program, we can use a similar recipe that specifies using the module file and tests.cpp (and not main.cpp):
$ g++ -std=c++20 -fmodules-ts library.cxx tests.cpp -o test-program.exe
Here is a test program that builds using the library defined on the previous page:
Listing 6.6.1. main.cpp (with module import)
There are now two paths to build a program using our library.cxx file. One path produces program.exe and the other produces test-program.exe:
Figure 6.6.2. We can build both the main program and the test program using the same library.

Note 6.6.2.

Depending on the development environment you are using outside of this book, the details of setting up two programs that build from the same files may vary. You may need to set up two separate β€œprojects” in your development environment or you may be able to set up one β€œproject” with multiple build targets.

Checkpoint 6.6.1.

Which is the true statements?
  • Each program must have exactly one main function.
  • All programs in a project must be compiled at the same time.
  • Different programs can make use of the same library code.
You have attempted of activities on this page.