I like working with gcovr on my Linux box to understand what is tested and what I have not. I have fallen into a pit where I cannot see the solution.
I have C-code like shown just below (save as main.c
). The code is made super simple - and the focus is in reality only the #if construction and how to work with coverage analysis for different compile setups.
/* Save as main.c */
#include <stdio.h>
void fct(int a)
{
// Define PRINTSTYLE to 0 or 1 when compiling
#if PRINTSTYLE==0
if (a<0) {
printf("%i is negative\n", a);
} else {
printf("%i is ... sorta not negative\n", a);
}
#else
if (a<0) {
printf("%i<0\n", a);
} else {
printf("%i>=0\n", a);
}
#endif
}
int main(void)
{
fct(1);
fct(-1);
return 0;
}
Which I can compile and do coverage test on Linux using e.g.
$ rm -f testprogram *.html *.gc??
$ gcc -o testprogram main.c \
-g --coverage -fprofile-arcs -ftest-coverage --coverage \
-DPRINTSTYLE=0
$ ./testprogram
$ gcovr -r . --html --html-details -o index.html
$ firefox index.main.c.html
This is nearly super - but what I want to do is to combine the test results for -DPRINTSTYLE=0
(see ahove) and -DPRINTSTYLE=1
- then I logically should get 100% coverage in the produced index.main.c.html
I fully understand that recompilation is needed in the middle.
How do I get 100% coverage with gcovr with ifdef code?
This is doable - but requires gcovr 4.2 (or later) as shown in https://gcovr.com/en/stable/guide.html#combining-tracefiles
First install or upgrade gcovr e.g. with
Then make sure that ~/.local/bin/ is in the $PATH.
Next run gcovr once for each configuration, and produce a JSON report:
Finally, combine the JSON reports using the -a/--add-tracefile mode and produce the desired report:
Reference: https://github.com/gcovr/gcovr/issues/338