GCOV的使用

GCOV的使用

gcov是什么?

Gcov is GCC Coverage 是一个测试代码覆盖率的工具

是一个命令行方式的控制台程序

伴随GCC发布,配合GCC共同实现对C/C++文件的语句覆盖和分支覆盖测试;

与程序概要分析工具(profiling tool,例如gprof)一起工作,可以估计程序中哪一段代码最耗时; 注:程序概要分析工具是分析代码性能的工具。

下面我们来讲解怎么使用gcov工具


[lzz@localhost exercise]$ gcc -g3 -fprofile-arcs -ftest-coverage openfile.c
[lzz@localhost exercise]$ ls
a.out  file  gdbscript.sh  openfile  openfile.c  openfile.gcno
[lzz@localhost exercise]$ ./a.out
open file success!

其中a.out就是我们生成的代码覆盖的调试文件,如果我们使用objdump -d a.out反汇编这个程序,就会发现,这样比起调试的程序在汇编中加入了大量的代码覆盖测试代码。然后我们使用gcov完成了执行代码覆盖。 我们使用gdb的方式强制执行某些分支语句。


[lzz@localhost exercise]$ gcov openfile.c
File‘openfile.c’
已执行的行数:85.71% (共 7 行)
Creating 'openfile.c.gcov'
[lzz@localhost exercise]$ gdb -x gdbscript.sh
GNU gdb (GDB) Fedora (7.5.1-38.fc18)
Copyright (C) 2012 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Breakpoint 1 at 0x400db0: file openfile.c, line 11.
 
Breakpoint 1, main (argc=1, argv=0x7fffffffe0b8) at openfile.c:11
11      if(-1 == fd)
open file error!
[Inferior 1 (process 7720) exited normally]
[lzz@localhost exercise]$ gcov openfile.c
openfile.c       openfile.c.gcov
[lzz@localhost exercise]$ gcov openfile.c
File‘openfile.c’
已执行的行数:100.00% (共 7 行)
Creating 'openfile.c.gcov'
 
[lzz@localhost exercise]$ cat openfile.c.gcov
        -:    0:Source:openfile.c
        -:    0:Graph:openfile.gcno
        -:    0:Data:openfile.gcda
        -:    0:Runs:2
        -:    0:Programs:1
        -:    1:#include
        -:    2:#include
        -:    3:#include <sys/types.h>
        -:    4:#include <sys/stat.h>
        -:    5:#include
        -:    6:#define FILE "/home/lzz/dslab/exercise/file"
        2:    7:int main(int argc,char **argv)
        -:    8:{
        2:    9:    int fd = 0 ;
        2:   10:    fd = open(FILE,O_CREAT,440);
        2:   11:    if(-1 == fd)
        -:   12:    {
        1:   13:        printf("open file error!\n");
        -:   14:    }
        -:   15:    else
        -:   16:    {
        1:   17:        printf("open file success!\n");
        -:   18:    }
        2:   19:    return 0;
        -:   20:}
        -:   21:

前面的数字就是这行代码执行的次数,可以很明确的反映每行代码执行频率。