← C++

C++ · 05 / 24

Headers, CMake and first unit tests

Build a multi-file project and verify business boundaries with GoogleTest.

  • Medium
  • Intermediate
  • 75 min

Prerequisites: Strings, vectors and standard algorithms, Classes, references, const and RAII

In this tutorial
  1. Separate the interface
  2. Calculate the boundary safely
  3. Configure the project
  4. Run the program
  5. Inspect the verification
  6. Test business promises
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

GCC with C++20 and CMake 3.25 or newer. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-21 on Linux x86_64. GoogleTest checks capacity boundaries and invalid values. The solution adds an empty vehicle with zero capacity.

Once a program has several files, the compiler needs to know which parts belong together. A header declares an interface and a source file implements it. CMake describes libraries, programs and tests. It does not replace the compiler. It generates build instructions for the selected build tool.

The learning rule checks whether additional cargo fits into a vehicle. This is an independent example. FactoryForge 0.1.0 carries one order per trip. The cargo rule provides a small, understandable subject for exact capacity, invalid input and integer-boundary tests.

Package contents and individual files

01Separate the interface

cargo.h declares canLoad. Its parameters represent current cargo, additional cargo and maximum capacity. Other files can call the function without copying its implementation. The header protection prevents duplicate declarations when headers are included repeatedly.

cargo.h · cppOpen file
#pragma once
bool canLoad(int current, int amount, int capacity);

02Calculate the boundary safely

The implementation rejects negative inputs and first checks that current is within capacity. It then compares amount against capacity - current. Adding current and amount could overflow for large int values. The selected check order avoids that invalid intermediate calculation.

cargo.cpp · cppOpen file
#include "cargo.h"
bool canLoad(int current, int amount, int capacity) {
  return current >= 0 && amount >= 0 && capacity >= 0 && current <= capacity &&
         amount <= capacity - current;
}

03Configure the project

Put all five files in one directory. CMakeLists.txt creates the cargo library, the lesson executable and cargo_tests. GoogleTest 1.15.2 is fetched into the build directory during the first configuration. Install CMake 3.25 or newer and Ninja, then run cmake -S . -B build -G Ninja followed by cmake --build build.

CMakeLists.txt · cmakeOpen file
cmake_minimum_required(VERSION 3.25)
project(CargoLesson LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_library(cargo cargo.cpp)
target_include_directories(cargo PUBLIC .)
add_executable(lesson main.cpp)
target_link_libraries(lesson PRIVATE cargo)
include(CTest)
include(FetchContent)
set(INSTALL_GTEST OFF CACHE BOOL "" FORCE)
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_Declare(googletest URL https://github.com/google/googletest/archive/refs/tags/v1.15.2.tar.gz DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
FetchContent_MakeAvailable(googletest)
add_executable(cargo_tests cargo_test.cpp)
target_link_libraries(cargo_tests PRIVATE cargo GTest::gtest_main)
add_test(NAME cargo COMMAND cargo_tests)

04Run the program

main.cpp checks two existing parcels plus three new parcels against capacity five. std::boolalpha prints true or false instead of a number. On Linux run ./build/lesson. On Windows run build\lesson.exe from the appropriate compiler environment.

main.cpp · cppOpen file
#include "cargo.h"
#include <iostream>
int main() {
  std::cout << std::boolalpha << "can_load=" << canLoad(2, 3, 5) << '\n';
}

Run / check

cmake -S . -B build -G Ninja
cmake --build build
./build/lesson
Expected result

can_load=true

05Inspect the verification

GoogleTest checks capacity boundaries and invalid values. The solution adds an empty vehicle with zero capacity.Run python3 run_checks.py from the extracted package. Compare the test expectations with the exercise before opening the solution.

cargo_test.cpp · cppOpen file
#include "cargo.h"
#include <gtest/gtest.h>
#include <limits>
TEST(Cargo, AcceptsExactCapacityAndRejectsOverflow) {
  EXPECT_TRUE(canLoad(2, 3, 5));
  EXPECT_FALSE(canLoad(2, 4, 5));
  EXPECT_FALSE(canLoad(std::numeric_limits<int>::max(), 1,
                       std::numeric_limits<int>::max()));
}
TEST(Cargo, RejectsNegativeInput) {
  EXPECT_FALSE(canLoad(-1, 1, 5));
  EXPECT_FALSE(canLoad(1, -1, 5));
}
Expected result

The example and automated solution pass. The stated manual checks remain separate.

06Test business promises

Run ctest --test-dir build --output-on-failure. Tests cover exact capacity, one parcel too many, negative values and the largest int boundary. A useful test expresses a promise to the caller rather than duplicating the function’s calculation.

cargo_test.cpp · cppOpen file
#include "cargo.h"
#include <gtest/gtest.h>
#include <limits>
TEST(Cargo, AcceptsExactCapacityAndRejectsOverflow) {
  EXPECT_TRUE(canLoad(2, 3, 5));
  EXPECT_FALSE(canLoad(2, 4, 5));
  EXPECT_FALSE(canLoad(std::numeric_limits<int>::max(), 1,
                       std::numeric_limits<int>::max()));
}
TEST(Cargo, RejectsNegativeInput) {
  EXPECT_FALSE(canLoad(-1, 1, 5));
  EXPECT_FALSE(canLoad(1, -1, 5));
}
Expected result

All Cargo tests pass.

Your exercise

Add tests for an empty vehicle with zero cargo and zero capacity. Deliberately break one boundary afterwards and observe the failed test.

Show the solution and explanation

canLoad(0, 0, 0) is valid and returns true. canLoad(0, 1, 0) returns false. Add an expectation for each. If the implementation accidentally rejects exact capacity, the existing boundary test fails. Restore the correct rule before continuing.

solution/cargo_test.cpp · cppOpen file
#include "cargo.h"
#include <gtest/gtest.h>
#include <limits>
TEST(Cargo, AcceptsExactCapacityAndRejectsOverflow) {
  EXPECT_TRUE(canLoad(2, 3, 5));
  EXPECT_FALSE(canLoad(2, 4, 5));
  EXPECT_FALSE(canLoad(std::numeric_limits<int>::max(), 1,
                       std::numeric_limits<int>::max()));
}
TEST(Cargo, RejectsNegativeInput) {
  EXPECT_FALSE(canLoad(-1, 1, 5));
  EXPECT_FALSE(canLoad(1, -1, 5));
}

TEST(Cargo, EmptyVehicleWithNoCapacity) {
  EXPECT_TRUE(canLoad(0, 0, 0));
  EXPECT_FALSE(canLoad(0, 1, 0));
}

Project context and sources

The first six examples are standalone teaching programs. Lessons 7 through 9 use the complete FactoryForge source snapshot. Code, exercises and verified simplifications are explained separately. The project page provides a source ZIP while the GitHub repository is not yet published.