GCOV(1)
๐ธ GCOV(1) ยท GNU manual ๐ธ
๐ธ NAME ๐ธ
Bestie, the whole name is just gcov - coverage testing tool ๐
๐ฆ SYNOPSIS ๐ฆ
gcov [-v|--version] [-h|--help]
[-a|--all-blocks]
[-b|--branch-probabilities]
[-c|--branch-counts]
[-d|--display-progress]
[-f|--function-summaries]
[-j|--json-format]
[-H|--human-readable]
[-k|--use-colors]
[-l|--long-file-names]
[-m|--demangled-names]
[-n|--no-output]
[-o|--object-directory directory|file]
[-p|--preserve-paths]
[-q|--use-hotness-colors]
[-r|--relative-only]
[-s|--source-prefix directory]
[-t|--stdout]
[-u|--unconditional-branches]
[-x|--hash-filenames]
files
๐ DESCRIPTION ๐
Okay so gcov is a test coverage program ๐ You use it together with GCC to analyze your programs so you can make more efficient, faster running code and sniff out the parts of your program nobody has tested ๐. It can also be a profiling tool that helps you figure out where your optimization efforts will hit your code the hardest ๐ฅ. You can pair it with the other profiling tool, gprof, to see which parts of your code are eating the most computing time โจ.
Profiling tools help you analyze your code's performance ๐ง. With a profiler like gcov or gprof, you can find out some basic performance stats, like:
- how often each line of code executes
- what lines of code are actually executed
- how much computing time each section of code uses
Once you know these things about how your code works when compiled, you can look at each module and see which ones should be optimized. gcov helps you figure out where to work on optimization ๐
.
Software developers also use coverage testing together with testsuites, to make sure software is actually good enough for a release ๐. Testsuites can verify that a program works as expected, while a coverage program checks how much of the program gets exercised by the testsuite ๐. Developers can then figure out what kinds of test cases need to be added to the testsuites for better testing and a better final product ๐ซถ.
You should compile your code without optimization if you plan to use gcov, because the optimization (by combining some lines of code into one function) may not give you as much info as you need to look for hot spots' where the code is using a great deal of computer time ๐. Likewise, because gcov` accumulates statistics by line (at the lowest resolution), it works best with a programming style that places only one statement on each line ๐. If you use complicated macros that expand to loops or to other control structures, the statistics are less helpful โ they only report on the line where the macro call appears ๐. If your complex macros behave like functions, you can replace them with inline functions to solve this problem โจ.
gcov creates a logfile called sourcefile.gcov which indicates how many times each line of a source file sourcefile.c has executed ๐. You can use these logfiles along with gprof to aid in fine-tuning the performance of your programs ๐ง. gprof gives timing information you can use along with the info you get from gcov โฑ๏ธ.
gcov works only on code compiled with GCC. It is not compatible with any other profiling or test coverage mechanism ๐ซ
๐ OPTIONS ๐
-a,--all-blocksโ This one's a gem ๐ It writes individual execution counts for every basic block. Normallygcovonly outputs execution counts for the main blocks of a line, but with this option you can tell if blocks within a single line aren't being executed ๐.-b,--branch-probabilitiesโ Writes branch frequencies to the output file and branch summary info to the standard output ๐ฆ. This lets you see how often each branch in your program was taken. Unconditional branches won't show up unless you also pass-u๐.-c,--branch-countsโ Writes branch frequencies as the number of branches taken, instead of the percentage of branches taken ๐ข.-d,--display-progressโ Shows the progress on the standard output โณ.-f,--function-summariesโ Outputs summaries for each function, on top of the file level summary ๐ง.-h,--helpโ Displays help about usinggcovon the standard output, then exits without doing any further processing ๐.-j,--json-formatโ Outputs the gcov file in an easy-to-parse JSON intermediate format that doesn't need source code to generate ๐ง . The JSON file is compressed with the gzip compression algorithm, and the files have the.gcov.json.gzextension ๐ฆ.
Here's the structure of the JSON, bestie ๐
{
"current_working_directory": "foo/bar",
"data_file": "a.out",
"format_version": "1",
"gcc_version": "11.1.1 20210510"
"files": ["$file"]
}
Fields of the root element have the following meanings:
current_working_directory: working directory where a compilation unit was compileddata_file: name of the data file (GCDA)format_version: semantic version of the formatgcc_version: version of the GCC compiler
Each file has the following form:
{
"file": "a.c",
"functions": ["$function"],
"lines": ["$line"]
}
Fields of the file element have the following meanings:
file_name: name of the source file
Each function has the following form:
{
"blocks": 2,
"blocks_executed": 2,
"demangled_name": "foo",
"end_column": 1,
"end_line": 4,
"execution_count": 1,
"name": "foo",
"start_column": 5,
"start_line": 1
}
Fields of the function element have the following meanings:
blocks: number of blocks that are in the functionblocks_executed: number of executed blocks of the functiondemangled_name: demangled name of the functionend_column: column in the source file where the function endsend_line: line in the source file where the function endsexecution_count: number of executions of the functionname: name of the functionstart_column: column in the source file where the function beginsstart_line: line in the source file where the function begins
Note that line numbers and column numbers start counting from 1. In the current implementation, start_line and start_column do not include any template parameters or the leading return type, but this is likely to be fixed in the future ๐ฎ.
Each line has the following form:
{
"branches": ["$branch"],
"count": 2,
"line_number": 15,
"unexecuted_block": false,
"function_name": "foo",
}
Branches are only present with the -b option. Fields of the line element have the following meanings:
count: number of executions of the lineline_number: line numberunexecuted_block: flag for whether the line contains an unexecuted block (not all statements on the line are executed)function_name: name of a function this line belongs to (for a line with inlined statements, this can be not set)
Each branch has the following form:
{
"count": 11,
"fallthrough": true,
"throw": false
}
Fields of the branch element have the following meanings:
count: number of executions of the branchfallthrough: true when the branch is a fall through branchthrow: true when the branch is an exceptional branch-H,--human-readableโ Writes counts in a human readable format, like24.6kโจ.-k,--use-colorsโ Colors the lines of code that have zero coverage ๐. We use red for non-exceptional lines and cyan for exceptional ones. The same colors get used for basic blocks with-a๐จ.-l,--long-file-namesโ Creates long file names for included source files. For example, if the header filex.hcontains code and was included ina.c, runninggcovona.cproduces an output file calleda.c##x.h.gcovinstead ofx.h.gcov๐. This is super useful ifx.his included in multiple source files and you want to see each one's individual contributions ๐งฉ. If you use the-poption, both the including and included file names will be complete path names ๐ฃ๏ธ.-m,--demangled-namesโ Shows demangled function names in the output. The default is mangled function names ๐ช.-n,--no-outputโ Doesn't create the gcov output file ๐ .-o directory|file,--object-directory directory,--object-file fileโ Tellsgcovwhere your coverage data is, either as the directory holding the gcov data files or as the object path name ๐. The.gcnoand.gcdadata files are searched for using this option. If you give a directory, the data files live in that directory and are named after the input file name, without its extension. If you give a file, the data files are named after that file, without its extension.-p,--preserve-pathsโ Keeps the complete path information in the names of generated.gcovfiles. Without this option, only the filename component is used. With it, all directories are used:/characters get translated to#characters,.directory components are removed, and unremoveable..components are renamed to^๐๏ธ. This is useful if your source files are spread across several different directories ๐.-q,--use-hotness-colorsโ Emits perf-like colored output for hot lines ๐ฅ. The legend for the color scale gets printed at the very beginning of the output file ๐ก๏ธ.-r,--relative-onlyโ Only outputs information about source files with a relative pathname (after source prefix elision). Absolute paths are usually system header files, and coverage of any inline functions in them is normally uninteresting ๐๏ธ.-s directory,--source-prefix directoryโ ๐งน A prefix for source file names that gets stripped off when gcov makes the output coverage files. This is super handy when you build in a separate directory and don't want the path to your source folder showing up in the output file names. Heads up: this prefix check happens before gcov decides whether the source file path is absolute. ๐บ๏ธ-t,--stdoutโ ๐บ Sends the output to standard output instead of writing output files. No files, just vibes in your terminal. โจ-u,--unconditional-branchesโ ๐ When branch probabilities are shown, this also includes the ones for unconditional branches. Normally those aren't very interesting, so they're left out by default. ๐ฅฑ-v,--versionโ ๐ท๏ธ Prints the gcov version number to standard output and exits right away, without doing any other processing. Quick check, then bye. ๐-w,--verboseโ ๐ Prints extra-detailed info about basic blocks and arcs. For when you need to go full detective mode. ๐ต๏ธโโ๏ธ-x,--hash-filenamesโ ๐งพ So, when you use--preserve-paths, gcov builds the output filename from the full path of the source file. That can get really long and overflow filesystem limits, which is not it. This option makes names likesource-file##md5.gcovinstead, wheresource-fileis just the final part of the filename and themd5bit is calculated from the full mangled name that would've been used otherwise. Think of it as the alternative to--preserve-pathsfor systems that have a filesystem limit. ๐ซถ
okay so, gcov needs to be run from the same current directory you were in when you invoked the compiler ๐ Otherwise it can't find your source files, and that's a whole mood. gcov creates files called mangledname.gcov in the current directory, and those hold the coverage info for the source file they match up with. You get one .gcov file for every source (or header) file that had code and was compiled to make the data files. The mangledname part is usually just the source file name, but it can get more complicated if you use the -l or -p options. Check those options for the deets. ๐
If you hand gcov multiple input files, the contributions from each one get summed up. Typically you'd pass it the same list of files you used for the final link of your executable. ๐
The .gcov files hold colon-separated fields along with your program's source code. The format goes like this:
<execution_count>:<line_number>:<source line text>
Extra block info might show up after each line if you ask for it with a command line option. The execution_count is - for lines that have no code. Unexecuted lines get marked with ##### or =====, depending on whether they can be reached by non-exceptional paths or only by exceptional paths, like C++ exception handlers. ๐ญ If you use the -a option, unexecuted blocks get marked with $$$$$ or %%%%%, depending on whether the basic block is reachable through non-exceptional or exceptional paths. Executed basic blocks that have a statement with a zero execution_count end with a * character, and they get colored magenta when you use the -k option. ๐ This functionality is not supported in Ada. ๐
โโ๏ธ
โ ๏ธ Lowkey confusing alert: GCC can completely remove the bodies of functions it doesn't need, for example if they're inlined everywhere. Those functions are marked with-, so it can look like they have no code at all. If you want to keep these functions around so gcov can properly show theirexecution_count, use the-fkeep-inline-functionsand-fkeep-static-functionsoptions. ๐ซ
Some of the lines at the start have a line_number of zero. These preamble lines look like this:
-:0:<tag>:<value>
The ordering and number of these preamble lines will be augmented as gcov development progresses --- so don't rely on them staying the same. Use the tag to find a particular preamble line instead. ๐
The additional block information looks like this:
<tag> <information>
The information is human readable, but it's designed to be simple enough for machines to parse too. ๐ค๐
When printing percentages, 0% and 100% only show up when the values are exactly 0% and 100%. Anything that would normally be rounded to 0% or 100% gets printed as the nearest non-boundary value instead. The boundaries are sacred, bestie. ๐ธ
When you're using gcov, you first have to compile your program with the special GCC option --coverage. This tells the compiler to generate the extra info gcov needs (basically a flow graph of your program) and to include extra code in the object files that collects the extra profiling info. These additional files get placed in the directory where the object file is located. ๐๏ธ
Running the program creates profile output. For each source file compiled with -fprofile-arcs, an accompanying .gcda file gets placed in the object file directory. ๐
Running gcov with your program's source file names as arguments now gives you a listing of the code along with how often each line ran. For example, if your program is called tmp.cpp, this is what you see with the basic gcov facility: โจ
$ g++ --coverage tmp.cpp -c
$ g++ --coverage tmp.o
$ a.out
$ gcov tmp.cpp -m
File 'tmp.cpp'
Lines executed:92.86% of 14
Creating 'tmp.cpp.gcov'
The file tmp.cpp.gcov holds the output from gcov. Here's a sample, and it's giving main character energy ๐:
-: 0:Source:tmp.cpp
-: 0:Working directory:/home/gcc/testcase
-: 0:Graph:tmp.gcno
-: 0:Data:tmp.gcda
-: 0:Runs:1
-: 0:Programs:1
-: 1:#include <stdio.h>
-: 2:
-: 3:template<class T>
-: 4:class Foo
-: 5:{
-: 6: public:
1*: 7: Foo(): b (1000) {}
------------------
Foo<char>::Foo():
#####: 7: Foo(): b (1000) {}
------------------
Foo<int>::Foo():
1: 7: Foo(): b (1000) {}
------------------
2*: 8: void inc () { b++; }
------------------
Foo<char>::inc():
#####: 8: void inc () { b++; }
------------------
Foo<int>::inc():
2: 8: void inc () { b++; }
------------------
-: 9:
-: 10: private:
-: 11: int b;
-: 12:};
-: 13:
-: 14:template class Foo<int>;
-: 15:template class Foo<char>;
-: 16:
-: 17:int
1: 18:main (void)
-: 19:{
-: 20: int i, total;
1: 21: Foo<int> counter;
-: 22:
1: 23: counter.inc();
1: 24: counter.inc();
1: 25: total = 0;
-: 26:
11: 27: for (i = 0; i < 10; i++)
10: 28: total += i;
-: 29:
1*: 30: int v = total > 100 ? 1 : 2;
-: 31:
1: 32: if (total != 45)
#####: 33: printf ("Failure\n");
-: 34: else
1: 35: printf ("Success\n");
1: 36: return 0;
-: 37:}
Note that line 7 shows up in the report multiple times. The first occurrence gives the total number of executions of the line, and the next two belong to the instances of the Foo class constructors. ๐ง As you can also see, line 30 contains some unexecuted basic blocks, so its execution count has an asterisk symbol. โญ
When you use the -a option, you get individual block counts, and the output looks like this: ๐ฆ
-: 0:Source:tmp.cpp
-: 0:Working directory:/home/gcc/testcase
-: 0:Graph:tmp.gcno
-: 0:Data:tmp.gcda
-: 0:Runs:1
-: 0:Programs:1
-: 1:#include <stdio.h>
-: 2:
-: 3:template<class T>
-: 4:class Foo
-: 5:{
-: 6: public:
1*: 7: Foo(): b (1000) {}
------------------
Foo<char>::Foo():
#####: 7: Foo(): b (1000) {}
------------------
Foo<int>::Foo():
1: 7: Foo(): b (1000) {}
------------------
2*: 8: void inc () { b++; }
------------------
Foo<char>::inc():
#####: 8: void inc () { b++; }
------------------
Foo<int>::inc():
2: 8: void inc () { b++; }
------------------
-: 9:
-: 10: private:
-: 11: int b;
-: 12:};
-: 13:
-: 14:template class Foo<int>;
-: 15:template class Foo<char>;
-: 16:
-: 17:int
1: 18:main (void)
-: 19:{
-: 20: int i, total;
1: 21: Foo<int> counter;
1: 21-block 0
-: 22:
1: 23: counter.inc();
1: 23-block 0
1: 24: counter.inc();
1: 24-block 0
1: 25: total = 0;
-: 26:
11: 27: for (i = 0; i < 10; i++)
1: 27-block 0
11: 27-block 1
10: 28: total += i;
10: 28-block 0
-: 29:
1*: 30: int v = total > 100 ? 1 : 2;
1: 30-block 0
%%%%%: 30-block 1
1: 30-block 2
-: 31:
1: 32: if (total != 45)
1: 32-block 0
#####: 33: printf ("Failure\n");
%%%%%: 33-block 0
-: 34: else
1: 35: printf ("Success\n");
1: 35-block 0
1: 36: return 0;
1: 36-block 0
-: 37:}
okay so in this mode ๐
each basic block only gets shown on one line, the last line of the block ๐ฆ. A multi-line block only adds to the execution count of that last line, and the other lines don't get shown as containing code, unless earlier blocks end on those lines ๐. The total execution count of a line is shown, and the lines after it show the counts for each individual block that ends there. After each block, its branch and call counts show up too, but only if you pass -b ๐
Because of how GCC instruments calls, a call count can show up after a line that has no individual blocks at all ๐ง And look, line 33 has a block that never ran ๐
When you use -b, your output looks like this ๐ธ
-: 0:Source:tmp.cpp
-: 0:Working directory:/home/gcc/testcase
-: 0:Graph:tmp.gcno
-: 0:Data:tmp.gcda
-: 0:Runs:1
-: 0:Programs:1
-: 1:#include <stdio.h>
-: 2:
-: 3:template<class T>
-: 4:class Foo
-: 5:{
-: 6: public:
1*: 7: Foo(): b (1000) {}
------------------
Foo<char>::Foo():
function Foo<char>::Foo() called 0 returned 0% blocks executed 0%
#####: 7: Foo(): b (1000) {}
------------------
Foo<int>::Foo():
function Foo<int>::Foo() called 1 returned 100% blocks executed 100%
1: 7: Foo(): b (1000) {}
------------------
2*: 8: void inc () { b++; }
------------------
Foo<char>::inc():
function Foo<char>::inc() called 0 returned 0% blocks executed 0%
#####: 8: void inc () { b++; }
------------------
Foo<int>::inc():
function Foo<int>::inc() called 2 returned 100% blocks executed 100%
2: 8: void inc () { b++; }
------------------
-: 9:
-: 10: private:
-: 11: int b;
-: 12:};
-: 13:
-: 14:template class Foo<int>;
-: 15:template class Foo<char>;
-: 16:
-: 17:int
function main called 1 returned 100% blocks executed 81%
1: 18:main (void)
-: 19:{
-: 20: int i, total;
1: 21: Foo<int> counter;
call 0 returned 100%
branch 1 taken 100% (fallthrough)
branch 2 taken 0% (throw)
-: 22:
1: 23: counter.inc();
call 0 returned 100%
branch 1 taken 100% (fallthrough)
branch 2 taken 0% (throw)
1: 24: counter.inc();
call 0 returned 100%
branch 1 taken 100% (fallthrough)
branch 2 taken 0% (throw)
1: 25: total = 0;
-: 26:
11: 27: for (i = 0; i < 10; i++)
branch 0 taken 91% (fallthrough)
branch 1 taken 9%
10: 28: total += i;
-: 29:
1*: 30: int v = total > 100 ? 1 : 2;
branch 0 taken 0% (fallthrough)
branch 1 taken 100%
-: 31:
1: 32: if (total != 45)
branch 0 taken 0% (fallthrough)
branch 1 taken 100%
#####: 33: printf ("Failure\n");
call 0 never executed
branch 1 never executed
branch 2 never executed
-: 34: else
1: 35: printf ("Success\n");
call 0 returned 100%
branch 1 taken 100% (fallthrough)
branch 2 taken 0% (throw)
1: 36: return 0;
-: 37:}
For each function, a line gets printed showing how many times it was called, how many times it returned, and what percentage of its blocks ran โจ
For each basic block, a line gets printed after the block's last line, describing the branch or call that ends the block ๐ A single source line can have several branches and calls listed if several blocks end on it. In that case, each one gets a number. There's no simple way to map those back to source constructs, sadly ๐ญ In general though, the lowest-numbered branch or call lines up with the leftmost construct on the source line.
For a branch, if it ran at least once, you get a percentage of how often it was taken divided by how often it was executed. If it never ran, you get the message "never executed" instead ๐ฅ
For a call, if it ran at least once, you get a percentage of how often it returned divided by how often it was called. This is usually 100%, but it can be lower for functions that call "exit" or "longjmp", since those might not return every single time ๐
The execution counts are cumulative ๐ If you run the example program again without deleting the .gcda file, the counts for every line get added onto the results from the previous run(s). That's lowkey super useful. You could collect data across a bunch of program runs as part of a test verification suite, or get more accurate long-term info over a huge number of runs ๐ง
The data in the .gcda files is saved right before the program exits ๐ช For each source file compiled with -fprofile-arcs, the profiling code first tries to read in an existing .gcda file. If that file doesn't match the executable (the number of basic block counts is different), it ignores the file's contents. Then it adds the new execution counts in and finally writes everything back to the file ๐พ
โจ Using gcov with GCC Optimization โจ
If you plan to use gcov to help optimize your code, you must first compile your program with the special GCC option --coverage ๐ฅ Other than that, you can use any other GCC options you want. But if you want to prove that every single line in your program was executed, you should not compile with optimization at the same time ๐
โโ๏ธ On some machines, the optimizer can eliminate some simple code lines by combining them with other lines. For example, code like this:
if (a != b)
c = 1;
else
c = 0;
can get compiled into one instruction on some machines. In that case, gcov has no way to calculate separate execution counts for each line, because there isn't separate code for each line ๐ญ So if you compiled the program with optimization, the gcov output looks like this:
100: 12:if (a != b)
100: 13: c = 1;
100: 14:else
100: 15: c = 0;
The output shows that this block of code, combined by optimization, ran 100 times. In one sense that's correct, because there was only one instruction representing all four of these lines. However, the output doesn't tell you how many times the result was 0 and how many times it was 1 ๐คทโโ๏ธ
Inlineable functions can create unexpected line counts ๐ Line counts are shown for the source code of the inlineable function, but what you see depends on where the function gets inlined, or whether it doesn't get inlined at all.
If the function isn't inlined, the compiler has to emit an out of line copy of the function in any object file that needs it. If fileA.o and fileB.o both contain out of line bodies of a particular inlineable function, they'll both also contain coverage counts for that function. When fileA.o and fileB.o get linked together, the linker will, on many systems, pick one of those out of line bodies for all calls to that function, and remove or ignore the other one. Unfortunately, it won't remove the coverage counters for the unused function body ๐ So when instrumented, all but one use of that function will show zero counts.
If the function is inlined in several places, the block structure in each location might not be the same. For instance, a condition might be calculable at compile time in some instances. Because the coverage of all the uses of the inline function gets shown for the same source lines, the line counts themselves might seem inconsistent ๐
Long-running applications can use the "__gcov_reset" and "__gcov_dump" facilities to limit profile collection to the part of the program you actually care about ๐ฏ Calling __gcov_reset(void) clears all run-time profile counters back to zero. Calling __gcov_dump(void) dumps the profile information collected up to that point into the .gcda output files. Instrumented applications use a static destructor with priority 99 to invoke the "__gcov_dump" function. So "__gcov_dump" runs after all user defined static destructors, as well as any handlers registered with "atexit" ๐ง
If an executable loads a dynamic shared object through dlopen functionality, you need -Wl,--dynamic-list-data to dump all the profile data ๐ซถ
The profiling run-time library reports various errors related to profile manipulation and profile saving. These get printed to standard error output, or to the file named by the GCOV_ERROR_FILE environment variable if you've set it ๐ If you want to terminate immediately after an error occurs, set the GCOV_EXIT_AT_ERROR environment variable. That can help you find profile clashing, which leads to a misleading profile ๐
โจ SEE ALSO โจ
gpl(7), gfdl(7), fsf-funding(7), gcc(1) and the Info entry for gcc ๐
โจ COPYRIGHT โจ
Copyright (c) 1996-2022 Free Software Foundation, Inc. ๐ธ
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation. The Invariant Sections are "GNU General Public License" and "Funding Free Software", the Front-Cover texts are (a) (see below), and the Back-Cover Texts are (b) (see below). A copy of the license is included in the gfdl(7) man page ๐
(a) The FSF's Front-Cover Text is:
A GNU Manual
(b) The FSF's Back-Cover Text is:
You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development.
That's the whole page, bestie ๐ Huge thanks to the source gcc-12, dated 2022-02-22, for being an absolute icon ๐ You're officially a gcov expert now. Go forth and profile ๐
โจ GCOV(1) signing off ๐ฆ
๐ฆ where this page comes from
- ubuntu jammy: gcc-12-i686-linux-gnu 12-20220222-1ubuntu1cross1
- ๐ girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms