【Linux GCC的代码覆盖率测试方法 gcov & lcov】

gcov & lcov简介

  • gcov执行函数覆盖、语句覆盖和分支覆盖。gcov伴随gcc 发布。gcc编译加入-fprofile-arcs -ftest-coverage 参数生成二进制程序,执行测试用例生成代码覆盖率信息。
     
  • lcov是gcov输出成果物图形化的前端工具,基于Html输出,并生成一棵完整的HTML树。输出包括概述、覆盖率百分比、图表,能快速浏览覆盖率数据。提供三个级别的视图:目录视图、文件视图、源码视图
  • 开源

gcov伴随gcc发行,所以安装gcc编译环境时就同时安装了。
:~# apt-get update
:~# apt-get install gcc g++

lcov的安装
:~# apt-get update
:~# apt-get install lcov

gcov的使用

用gcc编译时加上-fprofile-arcs -ftest-coverage选项
链接时也加上-fprofile-arcs -ftest-coverage选项
例:hello.c
:~# gcc -fprofile-arcs -ftest-coverage –o hello hello.c
上述编译/链接后会产生hello.gcno 和 目标执行文件hello
.gcno是由-ftest-coverage产生的,它包含了基本块图和相应的块的源码的行号的信息。
运行:
:~# ./hello
执行后生成hello. gcda文件
.gcda文件是由加了-fprofile-arcs编译参数的编译后的文件运行所产生的。
然后执行:
:~# gcov hello.c
File 'hello.c‘
Lines executed:83.33% of 6
hello.c:creating 'hello.c.gcov'
会生成hello.c.gcov文件
        -:    0:Source:hello.c
        -:    0:Graph:hello.gcno 
        -:    0:Data:hello.gcda
        -:    0:Runs:1
        -:    0:Programs:1
        -:    1:#include <stdio.h>
        -:    2:
        1:    3:int main(void)
        -:    4:{
        1:    5:    int    sts = 0;
        -:    6:
        1:    7:    if(sts)
        -:    8:    {
 ####:    9:        printf("Haha!\n"); 
        -:   10:    }
        -:   11:    else
        -:   12:    {
        1:   13:        printf("Hello world!\n"); 
        -:   14:    }
        -:   15: 
       1:   16:    return 0;
        -:   17:}
 

lcov的使用

收集覆盖率数据生成app.info文件
:~# lcov --directory . --capture --output-file hello.info
Capturing coverage data from .
Found gcov version: 4.4.5
Scanning . for .gcda files ...
Found 1 data files in .
Processing hello.gcda
Finished .info-file creation
Overall coverage rate:
  lines......: 83.3% (5 of 6 lines)
  functions..: 100.0% (1 of 1 function)
  branches...: 50.0% (1 of 2 branches)
此时会生成hello.info文件。
转换成html格式
:~# genhtml -o results hello.info 
Reading data file hello.info
Found 1 entries.
No common filename prefix found!
Writing .css and .png files.
Generating output.
Processing file /root/hello.c
Writing directory view page.
Overall coverage rate:
  lines......: 83.3% (5 of 6 lines)
  functions..: 100.0% (1 of 1 function)
  branches...: 50.0% (1 of 2 branches)
此时会生成存放HTML格式文档的results文件夹

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值