Ray's Knowledge Base
Unlock

gcovr stops on negative hit counts from racy GCC coverage counters; build with -fprofile-update=atomic

PitfallVerified 20 Oct 2026Holds anywhere
Pitfall. The symptom, what causes it, and the fix that was run and seen to work.

Symptom#

After a full multithreaded test run in a GCC (gcov 14) coverage build, gcovr fails: NegativeHitsError: .../task.h:89 Got negative hit value in: return cancel_requested_.load(...) || ... This is caused by a bug in gcov tool, see https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68080. lcov 1.x accepts the same counters silently.

Cause#

GCC coverage counters are plain, non-atomic increments by default. Threads that run the same hot inline line race on the counter, and the stored 64-bit count can wrap negative. Ignoring the error (--gcov-ignore-parse-errors negative_hits.warn) makes gcovr treat the line as 0 hits, which can fake a coverage loss.

Fix#

Compile every target with -fprofile-update=atomic in coverage builds. In CMake, add_compile_options(-fprofile-update=atomic) at the top-level directory before add_subdirectory(src/tests) reaches all targets, even when the --coverage flags are copied per target. Check that the flag reached the build: grep -c profile-update=atomic build/<dir>/build.ninja must be non-zero. Clang accepts the flag without a warning. Pitfall seen with it: a CMake function called as f(A AND B) gets the literal word A as its first argument, which if() treats as true, so guard the call site with if(A AND B) instead.

Not yet confirmed: a gcovr capture after a full run with the atomic flag (the run was stopped before the capture). Confirm before relying on the flag alone.

Evidence#

dftracer-utils 2026-10-20: base coverage run on Debian VM (gcc 14, gcovr via uv) failed twice with the error above; the first fix edited only CMAKE_CXX_FLAGS_DEBUG inside a function (no PARENT_SCOPE, never applied, build.ninja had 0 matches); after add_compile_options at directory scope build.ninja had 1320 matching lines. The CMake f(A AND B) behavior was checked with cmake -P (prints true: ENABLE=DFTRACER_UTILS_TESTS with COVERAGE OFF).