linux下codecoverage工具gcov/lcov使用

gcov是linux下进行代码覆盖测试的工具,随着gcc一起发布。lcov是gcov的图形化前端工具,根据gcov生成的内容,处理成一颗完整的html树,包括概述、覆盖率百分百、图标等轻便直观的内容。下面使用gcov和lcov进行一个简单的demo测试。

1.用gcov选项编译c/c++文件

test.cpp

#include <iostream>
using namespace std;
int main()
{
    for(int i=0;i<10;i++)
        cout<<"hello gcov"<<endl;
    cout<<"hello world"<<endl;
    return 0;
}
编译: g++ -fprofile-arcs -ftest-coverage test.cpp -o test

(也可以把-fprofile-arcs -ftest-coverage加入到makefile里面)


生成目标文件test和对应的test.gcno文件

.
|-- test
|-- test.cpp
`-- test.gcno

0 directories, 3 files

2.收集信息

执行该程序:./test

生成gcda文件

.
|-- test
|-- test.cpp
|-- test.gcda
`-- test.gcno

0 directories, 4 files

gcov生成覆盖信息:gcov test.cpp

.
|-- basic_ios.h.gcov
|-- char_traits.h.gcov
|-- ios_base.h.gcov
|-- iostream.gcov
|-- locale_facets.h.gcov
|-- ostream.gcov
|-- test
|-- test.cpp
|-- test.cpp.gcov
|-- test.gcda
`-- test.gcno

0 directories, 11 files

可以看到test.cpp.gcov的信息

        -:    0:Source:test.cpp
        -:    0:Graph:test.gcno
        -:    0:Data:test.gcda
        -:    0:Runs:1
        -:    0:Programs:1
        -:    1:#include <iostream>
        -:    2:using namespace std;
        1:    3:int main()
        -:    4:{
       11:    5:    for(int i=0;i<10;i++)
       10:    6:        cout<<"hello gcov"<<endl;
        1:    7:    cout<<"hello world"<<endl;
        1:    8:    return 0;
        3:    9:}
左边的数字表示某行执行了几次

3.用lcov转换成html可视化内容

lcov --capture --directory . --output-file testHtml.info --test-name testHtml

生成对应的info文件

Capturing coverage data from .
Found gcov version: 4.4.6
Scanning . for .gcda files ...
Found 1 data files in .
Processing test.gcda
Finished .info-file creation

.
|-- test
|-- test.cpp
|-- test.gcda
|-- test.gcno
`-- testHtml.info

0 directories, 5 files

生成html内容到result文件夹:genhtml -o result testHtml.info

Reading data file hello_test.info
genhtml: ERROR: cannot read file hello_test.info!
-bash-4.1# genhtml -o result testHtml.info
Reading data file testHtml.info
Found 7 entries.
Found common filename prefix "/usr/include/c++"
Writing .css and .png files.
Generating output.
Processing file /data/heyuxun/leetcode/test.cpp
Processing file 4.4.6/ostream
Processing file 4.4.6/iostream
Processing file 4.4.6/bits/ios_base.h
Processing file 4.4.6/bits/char_traits.h
Processing file 4.4.6/bits/locale_facets.h
Processing file 4.4.6/bits/basic_ios.h
Writing directory view page.
Overall coverage rate:
  lines......: 18.9% (7 of 37 lines)
  functions..: 21.4% (3 of 14 functions)

result里面的结果:


打开网页内容







是不是相当绚丽呢:)


  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值