GCOV(1)
๐ฆ GCOV(1): the gcov manual, GNU edition ๐ฆ
โจ NAME โจ
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 with GCC to analyze your programs, so you can make more efficient, faster-running code and find the untested parts of your program ๐ซถ You can also use gcov as a profiling tool to figure out where your optimization efforts will actually matter ๐ And if you pair it with the other profiling tool, gprof, you can figure out which parts of your code are eating the most computing time ๐ฅ
Profiling tools help you analyze how your code performs ๐ Using 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 behaves when compiled, you can look at each module and decide which ones need optimizing ๐ gcov helps you figure out where to put that optimization energy โจ
Software developers also use coverage testing alongside testsuites, to make sure software is actually good enough to release ๐ A testsuite checks that a program works as expected, while a coverage program checks how much of the program the testsuite actually exercises ๐ Developers can then see what kinds of test cases need to be added to the testsuites, for better testing and a better final product ๐
Heads up, bestie: you should compile your code without optimization if you plan to use gcov ๐ Optimization can combine some lines of code into one function, and then you might not get enough info to spot 'hot spots' where the code is chewing through a lot of computer time. Also, gcov tracks statistics by line (at the lowest resolution), so it works best with a style that puts only one statement on each line. If you use complicated macros that expand into loops or other control structures, the stats are less helpful ๐ญ They only report on the line where the macro call appears. If your complex macros behave like functions, you can swap them for inline functions to fix this ๐ง
gcov creates a logfile called sourcefile.gcov which shows how many times each line of a source file sourcefile.c has executed ๐งพ You can use these logfiles along with gprof to fine-tune the performance of your programs, since gprof gives timing info you can use alongside what you get from gcov ๐
Important: gcov only works on code compiled with GCC ๐ซ It is not compatible with any other profiling or test coverage mechanism.
๐ฆ OPTIONS ๐ฆ
-a,--all-blocksโ Write individual execution counts for every basic block ๐งฑ Normallygcovonly outputs execution counts for the main blocks of a line. With this option, you can tell whether blocks within a single line aren't being executed.-b,--branch-probabilitiesโ Write branch frequencies to the output file, and write branch summary info to the standard output ๐ฟ This lets you see how often each branch in your program was taken. Unconditional branches won't be shown unless you give the-uoption.-c,--branch-countsโ Write branch frequencies as the number of branches taken, instead of the percentage of branches taken ๐ข-d,--display-progressโ Display the progress on the standard output โณ-f,--function-summariesโ Output summaries for each function, in addition to the file-level summary ๐ง-h,--helpโ Display help about usinggcov(on the standard output), then exit without doing any further processing ๐-j,--json-formatโ Output the gcov file in an easy-to-parse JSON intermediate format that doesn't need the source code to generate ๐ค The JSON file is compressed with the gzip compression algorithm, and the files have the.gcov.json.gzextension.
The JSON is structured like this, bestie ๐
{
"current_working_directory": "foo/bar",
"data_file": "a.out",
"format_version": "1",
"gcc_version": "11.1.1 20210510"
"files": ["$file"]
}
Here's what the root element fields mean:
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 looks like this ๐
{
"file": "a.c",
"functions": ["$function"],
"lines": ["$line"]
}
For the file element, the field meaning is:
file_name: name of the source file
Each function looks like this ๐ญ
{
"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
}
For the function element, the fields mean:
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 count from 1 ๐ข In the current implementation, start_line and start_column don't include any template parameters or the leading return type, and that's likely to be fixed in the future ๐ฎ
Each line looks like this ๐
{
"branches": ["$branch"],
"count": 2,
"line_number": 15,
"unexecuted_block": false,
"function_name": "foo",
}
Branches only show up with the -b option ๐ฟ For the line element, the fields mean:
count: number of executions of the lineline_number: line numberunexecuted_block: flag whether the line contains an unexecuted block (not all statements on the line are executed)function_name: a name of a function this line belongs to (for a line with an inlined statements can be not set)
Each branch looks like this ๐ฑ
{
"count": 11,
"fallthrough": true,
"throw": false
}
For the branch element, the fields mean:
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โ Write counts in a human-readable format, like24.6kโจ-k,--use-colorsโ Color 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 when you use the-aoption.-l,--long-file-namesโ Create long file names for included source files ๐ For example, if the header filex.hcontains code and gets included ina.c, runninggcovona.cwill produce 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 the individual contributions. If you use the-poption, both the including and included file names will be complete path names ๐บ๏ธ-m,--demangled-namesโ Show demangled function names in the output ๐ช The default is to show mangled function names.-n,--no-outputโ Don't create thegcovoutput file ๐ซ-o directory|file,--object-directory directory,--object-file fileโ Tellgcoveither the directory containing the gcov data files, or the object path name ๐๏ธ The.gcnoand.gcdadata files are searched for using this option. If a directory is specified, the data files are in that directory and named after the input file name, without its extension. If a file is specified here, the data files are named after that file, without its extension.-p,--preserve-pathsโ Keep the complete path info in the names of the 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โ Emit perf-like colored output for hot lines ๐ฅ A legend of the color scale is printed at the very beginning of the output file ๐-r,--relative-onlyโ Only output 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 not that interesting ๐-s directory,--source-prefix directoryโ ๐๏ธ bestie, this one lets you chop a prefix off source file names before gcov makes the output coverage files ๐ It's a lifesaver when you build in a separate directory and don't want the path to your source folder showing up in the output names. Heads up: this prefix stripping happens before gcov checks whether the source file is absolute โจ-t,--stdoutโ ๐บ skip the output files entirely and dump everything straight to standard output ๐ฆ-u,--unconditional-branchesโ ๐ when branch probabilities are being given, this adds in the unconditional branches too. Honestly they're usually not that interesting, so gcov leaves them out by default ๐-v,--versionโ ๐ prints the gcov version number to standard output and then immediately exits, so no further processing happens ๐-w,--verboseโ ๐ง prints verbose info about basic blocks and arcs. Very detailed, very main-character ๐-x,--hash-filenamesโ ๐ฎ okay so, with--preserve-paths, gcov uses the full pathname of your source files to make the output filename, and that can get SO long it overflows filesystem limits ๐ญ This option fixes that by making names shaped likesource-file##md5.gcov, where source-file is the final filename part and the md5 bit is calculated from the full mangled name that would've been used otherwise. It's basically the alternative to--preserve-pathson systems that have a filesystem limit ๐ซถ
gcov needs to be run from the same current directory you were in when you invoked the compiler, or it won't be able to find your source files ๐ฅบ It produces files called mangledname.gcov in the current directory, and each one holds the coverage info for the source file it matches. 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 pass -l or -p. Check out those options for the deets ๐
If you run gcov with multiple input files, the contributions from each one get summed up together. Usually you'd pass it the same list of files you used for the final link of your executable โจ
The .gcov files have :-separated fields followed by the program's source code. The format looks like this:
<execution_count>:<line_number>:<source line text>
Extra block information can show up after each line when you ask for it with a command line option. The execution_count is - for lines with no code ๐ Unexecuted lines get marked ##### or =====, depending on whether they're reachable by non-exceptional paths or only exceptional paths (like C++ exception handlers, respectively) ๐ญ With the -a option, unexecuted blocks are marked $$$$$ or %%%%%, depending on whether the basic block is reachable via 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 with the -k option ๐ธ Heads up, this functionality is not supported in Ada ๐
Lowkey wild fact: GCC can completely remove the bodies of functions you don't need, like when they're inlined everywhere. Those functions get marked with -, which can be super confusing ๐ตโ๐ซ If you want to keep them around and let gcov properly show their execution_count, use the -fkeep-inline-functions and -fkeep-static-functions options ๐ซถ
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 do NOT 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% ๐
Any other values that would normally get rounded to 0% or 100% are instead printed as the nearest non-boundary value. No cap, that's a very thoughtful rule ๐ฆ
Okay, the real setup: when you use gcov, you first have to compile your program with a special GCC option, --coverage ๐ That tells the compiler to generate extra info gcov needs (basically a flow graph of the program), and it also adds extra code to the object files so they can generate the extra profiling information gcov wants. These additional files get placed in the directory where the object file is located ๐๏ธ
Running the program makes profile output get generated. For each source file compiled with -fprofile-arcs, there's an accompanying .gcda file that gets placed in the object file directory ๐
Now, if you run gcov with your program's source file names as arguments, you'll get a listing of the code with how often each line executed ๐ฅ For example, if your program is called tmp.cpp, this is what you see when you use 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 has the output from gcov. Here's a sample, bestie ๐
-: 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 shows the total number of executions of the line, and the next two belong to the instances of the class Foo constructors. You can also see that line 30 has some unexecuted basic blocks, so its execution count gets an asterisk ๐
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:}
In this mode, each basic block only shows up 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 won't be shown as containing code unless previous blocks end on those lines. The total execution count of a line is shown, and the lines after it show the counts for the individual blocks that end on that line. After each block, its branch and call counts appear too, but only if you pass the -b option ๐
Because of the way GCC instruments calls, a call count can pop up after a line with no individual blocks ๐ As you can see, line 33 contains a basic block that was not executed ๐
When you use the -b option, 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 the function is called, how many times it returns, and what percentage of the function's blocks were executed ๐ฆ
For each basic block, a line gets printed after the last line of that block, describing the branch or call that ends the block โจ There can be multiple branches and calls listed for a single source line if multiple basic blocks end on that line. In that case, each branch and call gets a number. There's no simple way to map these back to source constructs, but generally the lowest numbered branch or call corresponds to the leftmost construct on the source line ๐ง
For a branch, if it was executed at least once, a percentage gets printed showing the number of times the branch was taken divided by the number of times it was executed. Otherwise, you'll get the message never executed ๐ญ
For a call, if it was executed at least once, a percentage gets printed showing the number of times the call returned divided by the number of times the call was executed. This will usually be 100%, but it may be lower for functions that call exit or longjmp, since they may not return every time they're called ๐ธ
The execution counts are cumulative ๐ฅ If the example program were run again without removing the .gcda file, the count for each line would be added to the results of the previous run(s). This is potentially useful in a few ways. For example, it could be used to accumulate data over a number of program runs as part of a test verification suite, or to get more accurate long-term info over a large number of program runs ๐
The data in the .gcda files is saved immediately 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 the file doesn't match the executable (differing number of basic block counts), it ignores the contents of the file. Then it adds in the new execution counts and finally writes the data 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 a special GCC option, --coverage. Aside from that, you can use any other GCC options ๐ 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 be compiled into one instruction on some machines. In this case, there's no way for gcov to calculate separate execution counts for each line, because there isn't separate code for each line. Hence the gcov output looks like this if you compiled the program with optimization:
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, executed 100 times. In one sense this result is correct, because there was only one instruction representing all four of these lines. However, the output doesn't indicate how many times the result was 0 and how many times the result was 1 ๐ค
Inlineable functions can create unexpected line counts ๐ซ Line counts are shown for the source code of the inlineable function, but what gets shown depends on where the function is inlined, or whether it isn't inlined at all.
If the function is not inlined, the compiler must 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 will also both contain coverage counts for that function. When fileA.o and fileB.o are linked together, the linker will, on many systems, select one of those out of line bodies for all calls to that function, and remove or ignore the other. Unfortunately, it will not remove the coverage counters for the unused function body. Hence, 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 now be calculable at compile time in some instances. Because the coverage of all the uses of the inline function will be 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 restrict profile collection to the program region of interest ๐ฏ Calling __gcov_reset(void) will clear all run-time profile counters to zero, and calling __gcov_dump(void) will cause the profile information collected at that point to be dumped to .gcda output files. Instrumented applications use a static destructor with priority 99 to invoke the __gcov_dump function. Thus, __gcov_dump is executed after all user defined static destructors, as well as handlers registered with atexit.
If an executable loads a dynamic shared object viadlopenfunctionality,-Wl,--dynamic-list-datais needed to dump all profile data. โ ๏ธ
The profiling run-time library reports various errors related to profile manipulation and profile saving ๐ฌ Errors are printed to standard error output, or to the GCOV_ERROR_FILE file if that environment variable is used. If you want to terminate immediately after an error occurs, set the GCOV_EXIT_AT_ERROR environment variable. That can help you track down profile clashing, which leads to a misleading profile ๐
โจ SEE ALSO โจ
Go check out 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.
Okay bestie, that's the whole page ๐ซถ Pulled from gcc-12, last updated 2022-03-02, and this has been GCOV(1) signing off ๐ ๐ธ
๐ฆ where this page comes from
- ubuntu jammy: gcc-12-sh4-linux-gnu 12-20220302-1ubuntu1cross1
- ๐ girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms