gcov的覆盖率统计
创始人
2025-05-28 07:49:15

gcov的覆盖率统计

程序代码

先写个程序测试用例

#include 
#include int main(int argc, char *argv[])
{   if (argc >=2) {printf("=====argc>=2\n");return 1;}printf("helloworld begin\n");if (argc <2){printf("=====argc<2\n");return 2;}return 3;
}

执行:

gcc -fprofile-arcs -ftest-coverage helloworld_gcov.c

-fprofile-arcs -ftest-coverage告诉编译器生成gcov需要的额外信息,并在目标文件中插入gcov需要的extra profiling information。因此,该命令在生成可执行文件的同时生成gcov note文件(helloworld_gcov.gcno)。

收集更多信息指标

./a.out

数据报告

gcov helloworld_gcov.c

输出:

File 'helloworld_gcov.c'
Lines executed:66.67% of 9
Creating 'helloworld_gcov.c.gcov'

会生成新的文件 helloworld_gcov.c.gcov

        -:    0:Source:helloworld_gcov.c-:    0:Graph:helloworld_gcov.gcno-:    0:Data:helloworld_gcov.gcda-:    0:Runs:1-:    1:#include -:    2:#include -:    3:1:    4:int main(int argc, char *argv[])-:    5:{   1:    6:    if (argc >=2) {#####:    7:        printf("=====argc>=2\n");#####:    8:        return 1;-:    9:    }1:   10:    printf("helloworld begin\n");-:   11:1:   12:    if (argc <2){1:   13:        printf("=====argc<2\n");1:   14:        return 2;-:   15:    }#####:   16:    return 3;-:   17:}

其中#####表示未运行的行
每行前面的数字表示行运行的次数

文件名及含义:
helloworld_gcov.gcda 生成gcov data文件
helloworld_gcov.s 汇编语言源程序; 操作: 汇编
helloworld_gcov.c.gcov 可视化执行代码报告
helloworld_gcov.gcno .gcno是由-ftest-coverage产生的,它包含了重建基本块图和相应的块的源码的行号的信息

可视化及覆盖率

apt install lcov -y
或者
https://github.com/linux-test-project/lcov
make install
lcov --capture --directory . --output-file coverage.inf  genhtml coverage.info --output-directory out

image-20230315115827842

image-20230315115737098

合并覆盖率统计信息

./a.out i 4 执行的时候传个参数 程序执行的路径就会发生变化

lcov -c -d . o coverage2.info 生成新的info文件

genhtml -o 2 coverage2.info 生成新的html

genhtml -o combine coverage.info coverage2.info 进行合并info文件覆盖率

下图分别是1、2、合并。共三张图

image-20230315115737098

image-20230315121057205

image-20230315121107890

看了上图不知道你有没有发现啥异常,提示一下 我不能在同一文件夹下进行操作,必须加上rm helloworld_gcov.gcda 保障生成的是新的。

不信我再测试一下,不删除的情况下,进行生成info(更换参数)

./a.out i 1

image-20230315121621090

如果删除了gcda文件之后就正常了 (重在理解 不可照搬)

image-20230315133350616

image-20230315133908768

这是正常合并的内容。

编译器

持续更新

相关内容

热门资讯

记者手记|时代大潮里的笃行与担... 来源:新华社记者手记|时代大潮里的笃行与担当新华社记者韩梁 朱瑞卿 伍岳9月的新德里草木葱郁,阳光热...
被骂 “君子之贼” 高若讷有点...     ◎宋慧敏    北宋景祐三年(1036年)一个春日,谏官高若讷接到一封信,写信人是刚刚入朝任...
烂缦胡同:烟火气里涌动青春创业...     近日,在“全国文化中心建设巡礼”主题采访活动中,北京青年报记者走进北京市西城区牛街街道烂缦胡...
科技赋能实体 金融护航出海     9月9日至13日,2026年中国国际服务贸易交易会(以下简称服贸会)在北京首钢园举办,今年的...
湖北大学最新或2023(历届)...   1、考生自最新或2023(历届)4月1日起可在湖北大学招生信息网(http://zsxx.hub...