How to get 100% coverage with gcovr with ifdef code?

556 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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

pip install -U gcovr

Then make sure that ~/.local/bin/ is in the $PATH.

Next run gcovr once for each configuration, and produce a JSON report:

gcc -o testprogram main.c -g --coverage -DPRINTSTYLE=0
./testprogram
gcovr -r . --json run-1.json

gcc -o testprogram main.c -g --coverage -DPRINTSTYLE=1
./testprogram
gcovr -r . --json run-2.json

Finally, combine the JSON reports using the -a/--add-tracefile mode and produce the desired report:

gcovr --add-tracefile run-1.json --add-tracefile run-2.json --html-details coverage.html

Reference: https://github.com/gcovr/gcovr/issues/338