问题
I have problems understanding branch coverage in c++. Even for a simple program the branch coverage is 50%. When i use boost the branch coverage is below 20%.
Could someone explain me why this is happening? I am using
-fno-exceptions -g -O0 -fprofile-arcs -ftest-coverage -fPIC -Wall
compiler flags and gcovr
for generating the report. I also tried lcov
with exactly the same result
回答1:
This is just general C++ compiler weirdness. Both gcovr and lcov depend on the coverage data that GCC measures within the object code, and the compiler seems to insert some branch statements there.
I've looked at the disassembly of the generated code on Godbolt, and the compiler does indeed insert two jne
branch instructions under a section __static_initialization_and_destruction_0
. These disappear when you compile with -O1
.
Which optimization levels you should pick for your coverage measurements is a bit tricky. The more optimizations you enable, the more difficult it is to tie a coverage measurement to a specific source code line because the compiler may optimize much code away. But with C++, some optimizations are expected, and it's confusing when the compiler produces unnecessary code. As is the case here. Whatever level you choose, you won't generally be able to achieve full branch coverage.
The gcov documentation also discusses using gcov with GCC optimization. Gcov is used by gcovr to process the raw coverage data, and therefore has the same limitations.
However, gcovr performs some post-processing where it can exclude branches on lines that don't carry source code. Here, this would ignore any branches on the }
line when given the --exclude-unreachable-branches
flag.
来源:https://stackoverflow.com/questions/44655285/low-branch-coverage-especially-when-using-3rd-party-libs-ex-boost