在Linux下,可以使用Gcov工具生成覆盖率报告。Gcov是GNU的代码覆盖测试工具,它可以用来衡量测试用例对源代码的覆盖程度。
编写示例代码
下面是一个简单的示例:
假设你有一个C语言程序,源文件名为hello.c,其内容如下:
#include <stdio.h>
int main(int argc, char **argv)
{
for(int i=0; i<5; i++)
{
printf("Hello World\n");
}
return 0;
}
增加编译选项-fprofile-arcs -ftest-coverage编译成可执行文件
[test@localhost coverage]$ gcc -fprofile-arcs -ftest-coverage hello.c -o hello
[test@localhost coverage]$ ls -al
总用量 52
drwxrwxr-x. 2 test test 68 5月 21 20:01 .
drwxrwxr-x. 12 test test 4096 5月 21 19:51 ..
-rwxrwxr-x. 1 test test 33512 5月 21 20:00 hello
-rw-rw-r--. 1 test test 124 5月 21 19:56 hello.c
-rw-rw-r--. 1 test test 448 5月 21 20:00 hello.gcno
-rw-rw-r--. 1 test test 412 5月 21 19:55 Makefile
新增的编译选项将会生成gcno为后缀的文件。
运行程序
[test @localhost coverage]$ ./hello
Hello World
Hello World
Hello World
Hello World
Hello World
[test @localhost coverage]$ ls -al
总用量 56
drwxrwxr-x. 2 test test 86 5月 21 20:03 .
drwxrwxr-x. 12 test test 4096 5月 21 19:51 ..
-rwxrwxr-x. 1 test test 33512 5月 21 20:00 hello
-rw-rw-r--. 1 test test 124 5月 21 19:56 hello.c
-rw-rw-r--. 1 test test 184 5月 21 20:03 hello.gcda
-rw-rw-r--. 1 test test 448 5月 21 20:00 hello.gcno
-rw-rw-r--. 1 test test 412 5月 21 19:55 Makefile
运行hello程序,将会生成hello.gcda文件
gcov生成out文件
[test @localhost coverage]$ gcov -b -f -p -o . hello.c >hello.c.gcov.out
[test @localhost coverage]$
[test @localhost coverage]$
[test @localhost coverage]$
[test @localhost coverage]$ ll
总用量 60
-rwxrwxr-x. 1 test test 33512 5月 21 20:00 hello
-rw-rw-r--. 1 test test 124 5月 21 19:56 hello.c
-rw-rw-r--. 1 test test 555 5月 21 20:07 hello.c.gcov
-rw-rw-r--. 1 test test 301 5月 21 20:07 hello.c.gcov.out
-rw-rw-r--. 1 test test 184 5月 21 20:03 hello.gcda
-rw-rw-r--. 1 test test 448 5月 21 20:00 hello.gcno
-rw-rw-r--. 1 test test 412 5月 21 19:55 Makefile
生成info
lcov -d . -c -o lcov.info
生成网页
–output-direcotry选项用于指定输出html网也的目录名
–title选项:输出网页内容
–prefix选项:输出网页的保存路径
genhtml --show-details --legend --output-directory=coverage --title=hello--num-spaces=4 --prefix=. lcov.info