如何使用ifdef代码获得100%的gcovr覆盖率



我喜欢在我的Linux盒子上使用gcovr来了解哪些测试了,哪些没有测试。我陷入了一个看不到解决办法的深渊。

我有如下所示的C代码(另存为main.c(。代码变得超级简单,实际上重点只是#if构造以及如何在不同的编译设置中使用覆盖率分析。

/* 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 negativen", a);
} else {
printf("%i is ... sorta not negativen", a);
}
#else
if (a<0) {
printf("%i<0n", a);
} else {
printf("%i>=0n", a);
}
#endif
}

int main(void)
{
fct(1);
fct(-1);
return 0;
}

我可以使用例如在Linux上编译和进行覆盖测试

$ 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

这几乎是超级的,但我想做的是将-DPRINTSTYLE=0(请参阅ahove(和-DPRINTSTYLE=1的测试结果结合起来,然后从逻辑上讲,我应该在生成的index.main.c.html 中获得100%的覆盖率

我完全理解在中间需要重新编译。

如何使用带有ifdef代码的gcovr获得100%覆盖率?

这是可行的,但需要gcovr 4.2(或更高版本(,如中所示https://gcovr.com/en/stable/guide.html#combining-跟踪文件

首次安装或升级gcovr,例如使用

pip install -U gcovr

然后确保~/.local/bin/在$PATH中。

接下来,为每个配置运行一次gcovr,并生成一个JSON报告:

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

最后,使用-a/--add跟踪文件模式组合JSON报告,并生成所需的报告:

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

参考:https://github.com/gcovr/gcovr/issues/338

最新更新