Skip to main content

Coverage

The coverage module instruments targets for code coverage measurement and provides build targets to generate HTML reports. It supports both Clang and GCC, each with their own coverage toolchain, and is designed so that instrumentation can be enabled or disabled without modifying CMakeLists.txt.

Options

OptionDescriptionDefault
ENABLE_COVERAGEEnable coverage instrumentationOFF

When ENABLE_COVERAGE is OFF, the target_enable_coverage function is defined as a no-op. This means targets can call it unconditionally — the decision of whether to instrument is made at configure time, not in the build files.

Coverage is supported with Clang and GCC. Enabling it with any other compiler produces a fatal configuration error.

Compiler support

Clang

With Clang, the module uses source-based coverage via -fprofile-instr-generate and -fcoverage-mapping. This approach instruments the code at the AST level, producing precise line and region counts.

The coverage target executes tests through ctest --preset coverage, which must be defined in the project's CMakePresets.json. The preset generated by the scaffolding module includes one that sets the LLVM_PROFILE_FILE environment variable so that raw profile data is written to the build directory. After the tests finish, the target merges the generated .profraw files with llvm-profdata and generates an HTML report with llvm-cov show.

Required tools: llvm-profdata, llvm-cov.

GCC

With GCC, the module uses gcov-based coverage via the --coverage compiler and linker flag. The coverage target runs tests directly with ctest, then uses lcov to capture counters and genhtml to produce the HTML report.

The report is filtered to include only source files under src/ and include/, excluding test code and build system files. Branch coverage is enabled.

Required tools: lcov, genhtml.

Function reference

target_enable_coverage

target_enable_coverage(<target>)

Enables coverage instrumentation for a target. Apply it to both the library under test and the test executables so that all code paths are tracked.

add_library(mylib src/mylib.c)
target_enable_coverage(mylib)

add_executable(mylib-test tests/test.c)
target_enable_coverage(mylib-test)

Build targets

TargetDescription
coverageRuns tests and generates an HTML report
coverage-cleanRemoves all coverage data and reports

These targets are only available for top-level projects.

Variables defined

VariableDescription
COVERAGE_COMPILE_OPTIONSCompiler flags for coverage instrumentation
COVERAGE_LINK_OPTIONSLinker flags for coverage instrumentation
COVERAGE_REPORT_DIROutput directory for coverage reports

Usage

The scaffolding module generates a coverage preset that enables ENABLE_COVERAGE and BUILD_TESTING together:

make coverage

This configures, builds, runs tests, and generates the coverage report in a single step. The report is written to ${CMAKE_BINARY_DIR}/report/index.html.