TExcelTAD
Home › Modern CMake (with CTest & CPack) › CMake Exercises

CMake Exercises

Six exercises: three runnable models (JavaScript, edit and run them right here) and three broken CMake projects to fix. For the models, run the starter first: it prints wrong answers, which shows what the tests expect; complete the code marked TODO until the output matches the expected output. For the CMake projects, the starter session shows the real failure; the solution session (inside "Show solution") is the fixed project, also run for real. Try it on your own machine with CMake 3.25 or newer before opening the solution.

Exercise 1: Usage-requirement propagation

Topics: PUBLIC, PRIVATE & INTERFACE

Write includeDirsFor(target): the include directories a target is compiled with. A target uses its own PRIVATE and PUBLIC directories, plus the usage requirements of everything it links. A target's usage requirements are its PUBLIC and INTERFACE directories plus the usage requirements of everything it links PUBLIC or INTERFACE (but not PRIVATE).

js · try it yourself
const targets = {
  fmt:    { inc: [['INTERFACE', 'fmt/include']], links: [] },
  zlib:   { inc: [['PUBLIC', 'zlib/include']], links: [] },
  log:    { inc: [['PUBLIC', 'log/include'], ['PRIVATE', 'log/src']], links: [['PUBLIC', 'fmt']] },
  io:     { inc: [['PUBLIC', 'io/include']], links: [['PRIVATE', 'zlib'], ['PUBLIC', 'log']] },
  app:    { inc: [['PRIVATE', 'app/src']], links: [['PRIVATE', 'io']] },
};

function includeDirsFor(name) {
  // TODO: own PRIVATE+PUBLIC dirs, then the usage requirements of every linked target
  return [];
}

for (const t of ['log', 'io', 'app']) console.log(t.padEnd(4), includeDirsFor(t).join(' '));
log
io
app

Expected output:

text
log  log/include log/src fmt/include
io   io/include zlib/include log/include fmt/include
app  app/src io/include log/include fmt/include
Show solution
js
function usage(name) {
  const t = targets[name];
  const out = t.inc.filter(([s]) => s !== 'PRIVATE').map(([, d]) => d);
  for (const [scope, dep] of t.links) if (scope !== 'PRIVATE') out.push(...usage(dep));
  return out;
}
function includeDirsFor(name) {
  const t = targets[name];
  const out = t.inc.filter(([s]) => s !== 'INTERFACE').map(([, d]) => d);
  for (const [, dep] of t.links) out.push(...usage(dep));
  return [...new Set(out)];
}

app doesn't get zlib/include, because io links zlib PRIVATE.

Exercise 2: The header that wouldn't compile

Topics: Include Directories & Linking, Compile Features

app fails to build. The library's public header uses std::span (C++20) and a macro from a definition. Fix only the library's target_* lines (not the app's) so that app builds and prints sum = 6 (units: m).

bash · try it yourself
mkdir -p ex2/units/include/units && cd ex2
cat > units/include/units/sum.hpp <<'SRC'
#pragma once
#include <span>
#define UNITS_STR2(x) #x
#define UNITS_STR(x) UNITS_STR2(x)
int sum(std::span<const int> v);
inline const char* unit_name() { return UNITS_STR(UNITS_DEFAULT); }
SRC
cat > units/sum.cpp <<'SRC'
#include <units/sum.hpp>
int sum(std::span<const int> v) { int s = 0; for (int x : v) s += x; return s; }
SRC
cat > main.cpp <<'SRC'
#include <cstdio>
#include <units/sum.hpp>
int main() { int a[] = {1, 2, 3}; std::printf("sum = %d (units: %s)\n", sum(a), unit_name()); }
SRC
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Ex2 LANGUAGES CXX)
add_library(units units/sum.cpp)
target_include_directories(units PRIVATE units/include)
target_compile_features(units PRIVATE cxx_std_20)
target_compile_definitions(units PRIVATE UNITS_DEFAULT=m)
add_executable(app main.cpp)
target_link_libraries(app PRIVATE units)
CM
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build 2>&1 | grep -E 'error|FAILED' | sed 's#/home/learner/ex2/##'
FAILED: [code=1] CMakeFiles/app.dir/main.cpp.o
main.cpp:2:10: fatal error: units/sum.hpp: No such file or directory
Show solution

All three settings appear in the public header, so all three are PUBLIC:

bash · try it yourself
mkdir -p ex2/units/include/units && cd ex2
cat > units/include/units/sum.hpp <<'SRC'
#pragma once
#include <span>
#define UNITS_STR2(x) #x
#define UNITS_STR(x) UNITS_STR2(x)
int sum(std::span<const int> v);
inline const char* unit_name() { return UNITS_STR(UNITS_DEFAULT); }
SRC
cat > units/sum.cpp <<'SRC'
#include <units/sum.hpp>
int sum(std::span<const int> v) { int s = 0; for (int x : v) s += x; return s; }
SRC
cat > main.cpp <<'SRC'
#include <cstdio>
#include <units/sum.hpp>
int main() { int a[] = {1, 2, 3}; std::printf("sum = %d (units: %s)\n", sum(a), unit_name()); }
SRC
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Ex2 LANGUAGES CXX)
add_library(units units/sum.cpp)
target_include_directories(units PUBLIC units/include)
target_compile_features(units PUBLIC cxx_std_20)
target_compile_definitions(units PUBLIC UNITS_DEFAULT=m)
add_executable(app main.cpp)
target_link_libraries(app PRIVATE units)
CM
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build > /dev/null && ./build/app
sum = 6 (units: m)

Exercise 3: Version compatibility

Topics: Package Config Files

Implement sameMajorCompatible(packageVersion, requested) the way write_basic_package_version_file(... COMPATIBILITY SameMajorVersion) decides: the major versions must be equal, and the package must not be older than the request. Missing components of the request count as 0.

js · try it yourself
function sameMajorCompatible(pkg, req) {
  // TODO
  return false;
}

const pkg = '2.3.1';
for (const req of ['2', '2.3', '2.3.1', '2.3.2', '2.4', '1.9', '3.0']) {
  console.log(`find_package(X ${req.padEnd(5)}) with X ${pkg}: ${sameMajorCompatible(pkg, req) ? 'found' : 'rejected'}`);
}
find_package(X 2    ) with X 2.3.1: rejected
find_package(X 2.3  ) with X 2.3.1: rejected
find_package(X 2.3.1) with X 2.3.1: rejected
find_package(X 2.3.2) with X 2.3.1: rejected
find_package(X 2.4  ) with X 2.3.1: rejected
find_package(X 1.9  ) with X 2.3.1: rejected
find_package(X 3.0  ) with X 2.3.1: rejected

Expected output:

text
find_package(X 2    ) with X 2.3.1: found
find_package(X 2.3  ) with X 2.3.1: found
find_package(X 2.3.1) with X 2.3.1: found
find_package(X 2.3.2) with X 2.3.1: rejected
find_package(X 2.4  ) with X 2.3.1: rejected
find_package(X 1.9  ) with X 2.3.1: rejected
find_package(X 3.0  ) with X 2.3.1: rejected
Show solution
js
function sameMajorCompatible(pkg, req) {
  const p = pkg.split('.').map(Number);
  const r = req.split('.').map(Number);
  while (r.length < 3) r.push(0);
  if (p[0] !== r[0]) return false;
  for (let i = 0; i < 3; i++) if (p[i] !== r[i]) return p[i] > r[i];
  return true;
}

Exercise 4: Make the library exportable

Topics: BUILD_INTERFACE, INSTALL_INTERFACE & File Sets, Exporting Targets

This library refuses to generate. Fix it so the configure succeeds and cmake --install build --prefix ~/sdk installs the header and an export file whose include directory is ${_IMPORT_PREFIX}/include.

bash · try it yourself
mkdir -p ex4/include/clock && cd ex4
echo '#pragma once
long ticks();' > include/clock/clock.hpp
echo '#include <clock/clock.hpp>
long ticks() { return 42; }' > clock.cpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Clock LANGUAGES CXX)
include(GNUInstallDirs)
add_library(clock clock.cpp)
target_include_directories(clock PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
install(TARGETS clock EXPORT ClockTargets)
install(EXPORT ClockTargets NAMESPACE Clock:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Clock)
CM
cmake -S . -B build -G Ninja --log-level=NOTICE 2>&1 | grep -A4 'CMake Error'
CMake Error in CMakeLists.txt:
  Target "clock" INTERFACE_INCLUDE_DIRECTORIES property contains path:

    "/home/learner/ex4/include"
Show solution

Either the BUILD_INTERFACE/INSTALL_INTERFACE pair plus install(DIRECTORY), or (shown here) a header file set, which handles both and installs the header:

bash · try it yourself
mkdir -p ex4/include/clock && cd ex4
echo '#pragma once
long ticks();' > include/clock/clock.hpp
echo '#include <clock/clock.hpp>
long ticks() { return 42; }' > clock.cpp
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Clock LANGUAGES CXX)
include(GNUInstallDirs)
add_library(clock clock.cpp)
target_sources(clock PUBLIC FILE_SET HEADERS BASE_DIRS include FILES include/clock/clock.hpp)
install(TARGETS clock EXPORT ClockTargets FILE_SET HEADERS)
install(EXPORT ClockTargets NAMESPACE Clock:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Clock)
CM
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build > /dev/null
cmake --install build --prefix ~/sdk | grep -E 'clock.hpp|ClockTargets.cmake'
grep -A1 'APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES' ~/sdk/lib/cmake/Clock/ClockTargets.cmake | tail -n 1
-- Installing: /home/learner/sdk/include/clock/clock.hpp
-- Installing: /home/learner/sdk/lib/cmake/Clock/ClockTargets.cmake
      "${_IMPORT_PREFIX}/include"

Exercise 5: Which tests run?

Topics: Labels, Filters & Test Properties

Implement select(tests, opts): a test runs if it matches every -L label regex given (if any), matches no -LE regex, matches the -R name regex (if given) and doesn't match -E (if given).

js · try it yourself
const tests = [
  { name: 'parse.ok', labels: ['fast', 'parser'] },
  { name: 'parse.big', labels: ['slow', 'parser'] },
  { name: 'net.tls', labels: ['slow', 'net'] },
  { name: 'ui.click', labels: ['fast', 'gui'] },
];

function select(tests, { L = [], LE = [], R, E } = {}) {
  // TODO
  return tests.map((t) => t.name);
}

console.log(select(tests, { L: ['fast'] }).join(' '));
console.log(select(tests, { LE: ['slow'], E: 'ui' }).join(' '));
console.log(select(tests, { L: ['parser', 'slow'] }).join(' '));
console.log(select(tests, { R: '^(net|ui)', LE: ['gui'] }).join(' '));
parse.ok parse.big net.tls ui.click
parse.ok parse.big net.tls ui.click
parse.ok parse.big net.tls ui.click
parse.ok parse.big net.tls ui.click

Expected output:

text
parse.ok ui.click
parse.ok
parse.big
net.tls
Show solution
js
function select(tests, { L = [], LE = [], R, E } = {}) {
  const any = (labels, re) => labels.some((l) => new RegExp(re).test(l));
  return tests
    .filter((t) => L.every((re) => any(t.labels, re)))
    .filter((t) => !LE.some((re) => any(t.labels, re)))
    .filter((t) => (R ? new RegExp(R).test(t.name) : true))
    .filter((t) => (E ? !new RegExp(E).test(t.name) : true))
    .map((t) => t.name);
}

Exercise 6: A test that is supposed to fail

Topics: CTest Basics, Labels, Filters & Test Properties

validate must reject an empty argument with exit code 1, so the test rejects_empty should fail, and the suite should be green. Also give both tests the label cli, and make ctest -L cli the command that runs them. Change only CMakeLists.txt.

bash · try it yourself
mkdir -p ex6 && cd ex6
cat > validate.cpp <<'SRC'
#include <cstdio>
#include <cstring>
int main(int argc, char** argv) {
    if (argc < 2 || std::strlen(argv[1]) == 0) { std::puts("error: empty name"); return 1; }
    std::printf("ok: %s\n", argv[1]);
}
SRC
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Ex6 LANGUAGES CXX)
enable_testing()
add_executable(validate validate.cpp)
add_test(NAME accepts_name COMMAND validate ada)
add_test(NAME rejects_empty COMMAND validate "")
CM
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build > /dev/null
ctest --test-dir build -L cli 2>&1 | grep -E 'Test +#|tests passed|No tests'
ctest --test-dir build 2>&1 | grep -E 'Test +#|tests passed'
No tests were found!!!
1/2 Test #1: accepts_name .....................   Passed    0.00 sec
2/2 Test #2: rejects_empty ....................***Failed    0.00 sec
50% tests passed, 1 tests failed out of 2
Show solution
bash · try it yourself
mkdir -p ex6 && cd ex6
cat > validate.cpp <<'SRC'
#include <cstdio>
#include <cstring>
int main(int argc, char** argv) {
    if (argc < 2 || std::strlen(argv[1]) == 0) { std::puts("error: empty name"); return 1; }
    std::printf("ok: %s\n", argv[1]);
}
SRC
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Ex6 LANGUAGES CXX)
enable_testing()
add_executable(validate validate.cpp)
add_test(NAME accepts_name COMMAND validate ada)
add_test(NAME rejects_empty COMMAND validate "")
set_tests_properties(accepts_name rejects_empty PROPERTIES LABELS cli)
set_tests_properties(rejects_empty PROPERTIES WILL_FAIL TRUE)
CM
cmake -S . -B build -G Ninja --log-level=NOTICE > /dev/null
cmake --build build > /dev/null
ctest --test-dir build -L cli 2>&1 | grep -E 'Test +#|tests passed'
1/2 Test #1: accepts_name .....................   Passed    0.00 sec
2/2 Test #2: rejects_empty ....................   Passed    0.00 sec
100% tests passed out of 2

A stricter alternative to WILL_FAIL is PASS_REGULAR_EXPRESSION "error: empty name", which also checks why it failed.

Test yourself

In Exercise 2, why must cxx_std_20 be PUBLIC rather than PRIVATE?

  1. PRIVATE features are ignored
  2. The public header uses std::span, so every consumer compiling that header needs C++20 too
  3. PUBLIC is faster
  4. Only executables can have PRIVATE features

In Exercise 4, what was CMake protecting the consumers from?

  1. A missing library
  2. An installed package pointing at the author's source directory
  3. A wrong version
  4. A circular dependency