A project outgrows the single compile command, and then two things need to happen. The code has to be split into a layout that makes sense, and the build has to be described in a file so that everybody builds it the same way. CMake is the usual way to describe the build.
The previous lesson in this module covered "How Do You Write Tests That Catch Real Bugs?", and the next lesson in this module is about "Which C++ Bugs Appear Again and Again in Code Review?".
From a command line to a build file
A small project can be built with one command.
g++ -std=c++17 -Wall -Wextra main.cpp inventory.cpp -o inventoryAnd CMake replaces that command with a description of the project that generates the right commands for your platform.
cmake_minimum_required(VERSION 3.16)
project(inventory LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
add_executable(inventory
src/main.cpp
src/inventory.cpp
)
target_include_directories(inventory PRIVATE include)
if(MSVC)
target_compile_options(inventory PRIVATE /W4)
else()
target_compile_options(inventory PRIVATE -Wall -Wextra -Wpedantic)
endif()A folder structure that scales
The conventional layout separates the public interface from the implementation, the tests and the build output.
inventory/
├── CMakeLists.txt
├── include/
│ └── inventory.hpp the public interface
├── src/
│ ├── main.cpp the entry point
│ └── inventory.cpp the implementation
├── tests/
│ ├── CMakeLists.txt
│ └── test_inventory.cpp
├── data/ sample data files
└── build/ generated, never committedTargets and libraries
Naming them clearly means that the dependencies between them are explicit.
# A library of reusable code.
add_library(inventory_core STATIC
src/inventory.cpp
)
target_include_directories(inventory_core PUBLIC include)
# The command line program that uses it.
add_executable(inventory_cli
src/main.cpp
)
target_link_libraries(inventory_cli PRIVATE inventory_core)Out-of-source builds
And it keeps the generated files out of the way, it lets you have several build configurations at once, and it makes "delete the build directory" a complete reset.
cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failureAdding tests
CMake has a built-in test runner, and registering a test is two lines.
# tests/CMakeLists.txt
add_executable(inventory_tests
test_inventory.cpp
)
target_link_libraries(inventory_tests PRIVATE inventory_core)
add_test(NAME inventory_tests COMMAND inventory_tests)And in the top-level file you add these two lines.
enable_testing()
add_subdirectory(tests)Build configurations
CMake handles the difference between a debug build and a release build with a single flag.
cmake -S . -B build-debug -DCMAKE_BUILD_TYPE=Debug
cmake -S . -B build-release -DCMAKE_BUILD_TYPE=ReleaseThe pieces before the build file exists
And here is the separation that lets the tests link against the library instead of duplicating its code.
#include <iostream>
#include <string>
#include <vector>
// inventory.hpp declares:
struct Item {
std::string sku;
int quantity;
};
int total_quantity(const std::vector<Item>& items);
// inventory.cpp defines:
int total_quantity(const std::vector<Item>& items) {
int total = 0;
for (const Item& item : items) {
total += item.quantity;
}
return total;
}
// main.cpp uses:
int main() {
std::vector<Item> items = {{"A-100", 5}, {"B-200", 3}};
std::cout << "total: " << total_quantity(items) << '\n';
return 0;
}The output shows the library function being called from the executable.
total: 8A library and an executable side by side
The library exposes a header, and the executable includes it and links against the compiled library.
// inventory.hpp — the public interface
#include <string>
#include <vector>
struct Item {
std::string sku;
int quantity;
};
int total_quantity(const std::vector<Item>& items);// inventory.cpp — the implementation
#include "inventory.hpp"
int total_quantity(const std::vector<Item>& items) {
int total = 0;
for (const Item& item : items) {
total += item.quantity;
}
return total;
}// main.cpp — the program that uses the library
#include <iostream>
#include "inventory.hpp"
int main() {
std::vector<Item> items = {{"A-100", 5}, {"B-200", 3}};
std::cout << "total: " << total_quantity(items) << "\n";
return 0;
}A complete top-level file
Putting it together, a realistic top-level file looks like this.
cmake_minimum_required(VERSION 3.16)
project(inventory VERSION 1.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
option(INVENTORY_BUILD_TESTS "Build the unit tests" ON)
add_library(inventory_core STATIC
src/inventory.cpp
src/storage.cpp
)
target_include_directories(inventory_core PUBLIC include)
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
target_compile_options(inventory_core PRIVATE -Wall -Wextra -Wpedantic)
endif()
add_executable(inventory_cli
src/main.cpp
)
target_link_libraries(inventory_cli PRIVATE inventory_core)
if(INVENTORY_BUILD_TESTS)
enable_testing()
add_subdirectory(tests)
endif()Quick reference
- The CMake file describes the project, and it generates the commands for your platform.
- The
add_librarymakes the reusable code and theadd_executablemakes the program. - The
target_link_librariessays which target uses which, and thePRIVATEor thePUBLICsays who can see the headers. - The include folder holds the public interface and the src folder holds the implementation.
- You build out of the source, so the build directory can be deleted at any time.
- You register the tests with the
add_testand you run them with thectest.
Try it yourself: take a program that is in two files and split it into a header and two sources. Then write the CMake file that builds it, and check that the output is the same. Next, split the program into a library and an executable, and write a test that links against the library. Finally, build it twice with the two different build types and compare the sizes of the two binaries.