CMake and testing
CMake describes targets and dependencies, and CTest runs your test suite.
- Describe build units as targets and attach sources and dependencies to them.
- Link the Catch2 or GoogleTest library into a test executable.
- Register tests with CTest so one command runs them all.
- Set the C++ standard explicitly so the build is reproducible.
In plain English
CMake is a build tool that describes what to build and how, independent of any single compiler or IDE. A target is a named thing CMake can build, such as an executable or a library, and you attach sources, options and dependencies to it. A test framework such as Catch2 or GoogleTest lets you write assertions that check behaviour and report failures automatically. CMake can discover and register those tests so a single command runs them all. Writing tests before or alongside code turns a vague feature into a list of facts the program must satisfy.
Step by step
- 1Write a CMakeLists.txt with cmake_minimum_required and project.
- 2Set the C++ standard to 20 and require it.
- 3Create a test executable target and link the Catch2 or GoogleTest library.
- 4Register the test with CTest using add_test.
- 5Configure, build, then run ctest to see the results.
cmake_minimum_required(VERSION 3.20)
project(edubyte_test CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Catch2 3 REQUIRED)
add_executable(lesson_tests test/lesson_test.cpp)
target_link_libraries(lesson_tests PRIVATE Catch2::Catch2WithMain)
include(CTest)
add_test(NAME lesson_tests COMMAND lesson_tests)Common mistakes
- Forgetting to link the test framework library leaves undefined references at link time.
- Registering a test without include(CTest) or enable_testing() means ctest will not find it.
- Hardcoding absolute paths in CMake breaks the build for anyone else who clones the project.
- Skipping assertions for edge cases means the tests pass while the feature still fails in real use.
Register a test target
Write the CMake lines to create an executable target named lesson_tests from test/lesson_test.cpp, link Catch2::Catch2WithMain, and register it with add_test.
add_executable(lesson_tests test/lesson_test.cpp)Which CMake command registers an executable with CTest?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.