1、gcov
Linux下测试代码覆盖率工具,属于gcc工具集,不需要单独安装;
gcov -v //查看本编译环境下的gcov版本
2、lcov
lcov属于gcov的图形化工具,可转换为html格式的代码覆盖率报告,需要自己安装,网址如下
https://sourceforge.net/projects/ltp/files/Coverage%20Analysis/
3、使用gcov的阶段
(1)开启gcov功能。在makefile文件中加入-fprofile-arcs -ftest-coverage
-ftest-coverage:在编译时会产生.gcno文件,包含重建基本图块和相应的块的源代码的行号信息;
-fprofile-arcs:在运行编译的程序时会产生.gcda文件,包含弧跳变的次数信息。
实例程序test.c:
#include<stdio.h>
int main(void)
{
int i,total;
total=0;
for(i=0;i<10;i++)
total+=i;
if (total!=45)
printf("failure\n");
else
printf("success\n");
return 0;
}
test.c的makefile文件(主要是加入了-fprofile-arcs和-ftest-coverage):
all:
gcc -Wall -O0 -fprofile-arcs -ftest-coverage -o test test.c
clean: ## Clean all generate files
$(RM) test *.out *.o *.so *.gcno *.gcda *.gcov lcov-report gcovr-report
在编译后会出现可执行文件test和test.gcno,此时输入命令
gcov test.c
会生成原始的代码覆盖率文件test.gcov,因为此时没有运行test的可执行文件,所以没有test.gcda的统计数据,覆盖率为0。
(2)运行gcov会生成test.gcda文件,其中包含代码覆盖率信息
其中#####表示未运行的行
每行前面的数字表示行运行的次数
然后主要是lcov -c -d . -o test.info
然后genhtml -o 111 test.info
即可查看文件index-html文件。