I have a unit testing environment for C software that uses gcc14 and gcovr.
I would like it to detect unreachable code.
For instance, with the actual configuration (-fcondition-coverage --coverage
),
the following example would be 100% covered, even though the 'foo()' call is not reachable because after the return, and the 'bar()' call is not reachable because the flag NOT_DEFINED_FLAG
is... not defined.
int fun(void){
int ret = blah();
#ifdef NOT_DEFINED_FLAG
ret = bar(); // unreachable
#endif
return ret;
ret = foo();// unreachable
}
tested with
assert (0 == fun());
edit:
Giving some precision here. What I want to achieve here is :
I said I was using gcc14 and gcovr, but it does not mean I expect gcovr, gcov or gcc to do the job, I'm opened to all sort of solutions
Firstly, your goal of detecting unreachable code with gcovr doesn't seem useful. The execution count of unreachable code is trivially zero.
Using gcov (the text-based output and backend for gcovr), we can generate a file with the source code with an execution count next to each line. If a line is never executed it is shown as "#####". If it is not executable (whitespace, comments, a single brace, etc.) it is shown as "-".
Your first unreachable code segment (in the ifdef) is shown as not executable as there is no code generated from it. The pre-processor prunes this away before compilation so it may as well not exist as far as the compiler is concerned. It gets a dash.
Your second unreachable code segment (after returning) is removed by the compiler even at -O0 in my testing. This means the line is not executable and gcov gives it a dash.
The definitions of foo and bar will generally be kept by the compiler in case other compilation units need it. Even if it is not needed, as long as it generates some instruction at compilation, gcov can track it. So it will get an execution count.