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里面的结果:
打开网页内容
是不是相当绚丽呢:)