GCOV(1)
๐ GCOV(1) ๐
Heyyy bestie ๐ซถ this is the GNU manual page for gcov, and I'm about to make it make sense โจ
โจ NAME โจ
gcov - coverage testing tool ๐ฆ
๐ SYNOPSIS ๐
Here's how you call it, no cap ๐
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 write more efficient, faster running code and find the parts of your program nobody has tested yet ๐. It's also a profiling tool, so it helps you figure out where your optimization efforts will actually glow up your code โจ. 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 ๐. 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 this stuff about how your code behaves when it's compiled, you can look at each module and see which ones need optimizing. gcov helps you decide where to put your optimization energy ๐
Software devs also use coverage testing alongside testsuites, to make sure software is actually good enough for a release ๐. Testsuites check that a program works as expected, while a coverage program checks how much of the program the testsuite actually exercises ๐งช. Devs can then figure out what kinds of test cases to add to the testsuites for better testing and a better final product ๐.
You should compile without optimization if you plan to use gcov ๐
. Optimization combines some lines of code into one function, so you might not get enough info to find the hot spots' where the code is burning a ton of computer time ๐ฅ. Also, gcov` tracks stats 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 get less helpfulโthey only report on the line where the macro call appears ๐ญ. If your complex macros behave like functions, swap them out for inline functions to fix that ๐ฆ.
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 ๐ฏ. gprof gives timing info you can use alongside what you get from gcov ๐ฐ๏ธ.
gcov works only on code compiled with GCC ๐ซ. It's not compatible with any other profiling or test coverage mechanism, so don't even try ๐
.
โจ OPTIONS โจ
-a,--all-blocksโ Dump the execution count for every single basic block ๐งฑ. Normallygcovonly outputs counts for the main blocks of a line. With this option, you can spot whether blocks inside a single line aren't getting executed ๐.-b,--branch-probabilitiesโ Write branch frequencies to the output file, and write branch summary info to standard output ๐ฟ. This lets you see how often each branch in your program got taken. Unconditional branches won't show up unless you also pass-u๐.-c,--branch-countsโ Write branch frequencies as the number of branches taken, instead of the percentage of branches taken ๐ข.-d,--display-progressโ Show the progress on standard output โณ.-f,--function-summariesโ Output summaries for each function on top of the file-level summary ๐ง.-h,--helpโ Show help about usinggcovon standard output, then exit without doing any further processing ๐.-j,--json-formatโ Output the gcov file in an easy-to-parse JSON intermediate format ๐งพ. It doesn't need source code to generate ๐. The JSON file is compressed with the gzip algorithm, and the files end in.gcov.json.gz๐. The full breakdown is below, bestie ๐.
๐งพ -j, --json-format, the full tea ๐งพ
Here's the structure of the JSON ๐ซฃ
{
"current_working_directory": <current_working_directory>,
"data_file": <data_file>,
"format_version": <format_version>,
"gcc_version": <gcc_version>
"files": [<file>]
}
The fields of the root element mean the following:
current_working_directory: the working directory where a compilation unit was compiled ๐data_file: the name of the data file (GCDA) ๐๏ธformat_version: the semantic version of the format ๐gcc_version: the version of the GCC compiler ๐ ๏ธ
Each file has this form:
{
"file": <file_name>,
"functions": [<function>],
"lines": [<line>]
}
The fields of the file element mean the following:
file_name: the name of the source file ๐
Each function has this form:
{
"blocks": <blocks>,
"blocks_executed": <blocks_executed>,
"demangled_name": "<demangled_name>,
"end_column": <end_column>,
"end_line": <end_line>,
"execution_count": <execution_count>,
"name": <name>,
"start_column": <start_column>
"start_line": <start_line>
}
The fields of the function element mean the following:
blocks: the number of blocks that are in the function ๐งฑblocks_executed: the number of executed blocks of the function โdemangled_name: the demangled name of the function ๐ชend_column: the column in the source file where the function ends ๐end_line: the line in the source file where the function ends ๐execution_count: the number of executions of the function ๐name: the name of the function ๐ท๏ธstart_column: the column in the source file where the function begins ๐start_line: the line in the source file where the function begins ๐
Line numbers and column numbers both count from 1 ๐ข. In the current implementation,start_lineandstart_columndon't include any template parameters or the leading return type, but that's likely to get fixed in the future ๐ฎ.
Each line has this form:
{
"branches": [<branch>],
"count": <count>,
"line_number": <line_number>,
"unexecuted_block": <unexecuted_block>
"function_name": <function_name>,
}
Branches only show up when you use the -b option ๐ฟ. The fields of the line element mean the following:
count: the number of executions of the line ๐line_number: the line number ๐ขunexecuted_block: a flag for whether the line contains an unexecuted block (not all statements on the line were executed) ๐ฉfunction_name: the name of a function this line belongs to (for a line with inlined statements, this can be not set) ๐งฉ
Each branch has this form:
{
"count": <count>,
"fallthrough": <fallthrough>,
"throw": <throw>
}
The fields of the branch element mean the following:
count: the number of executions of the branch ๐fallthrough:truewhen the branch is a fall through branch โฌ๏ธthrow:truewhen 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, then 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 contribution ๐. If you use the-poption, both the including and included file names will be complete path names ๐บ๏ธ.-m,--demangled-namesโ Display demangled function names in the output ๐ช. The default is to show mangled function names ๐.-n,--no-outputโ Don't create the gcov output file ๐ซ๐.-o directory|file,--object-directory directory,--object-file fileโ Tell gcov where to find the gcov data files, by specifying either the directory that holds them or the object path name ๐๏ธ. The.gcnoand.gcdadata files are searched for using this option ๐. If you specify a directory, the data files live in that directory and are named after the input file name, minus its extension ๐. If you specify a file here, the data files are named after that file, minus its extension ๐ฏ.-s directory,--source-prefix directoryโ okay so this one is a prefix chopper โ๏ธ๐ It trims a prefix off the source file names before gcov makes the output coverage files. It's super handy when you build in a separate directory and don't want the path to the source directory showing up in your output names. Also, this prefix detection happens before gcov checks whether the source file is absolute ๐ซถ-t,--stdoutโ no files, bestie ๐จ๏ธ Everything gets printed to standard output instead of going into output files.-u,--unconditional-branchesโ when branch probabilities are given, this also includes the ones for unconditional branches ๐ Normally those aren't very interesting, so they're left out by default.-v,--versionโ shows the gcov version number on standard output and then exits immediately, no other processing ๐ฆ-w,--verboseโ prints verbose info about basic blocks and arcs ๐ง โจ-x,--hash-filenamesโ okay, this one is a lifesaver ๐ญ When you use--preserve-paths, gcov builds output filenames from the full pathname of the source files, and those can get so long they overflow filesystem limits. This option makes names of the formsource-file##md5.gcov, where source-file is the final filename part and md5 is calculated from the full mangled name that would've been used otherwise. It's the alternative to--preserve-pathson systems that have a filesystem limit ๐
gcov needs to be run with the current directory the same as the one 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 those contain the coverage info for the source file they belong to. You get one .gcov file for every source (or header) file that had code compiled into the data files. The mangledname part is usually just the source file name, but it can get more complicated if -l or -p are given. Check those options for the details ๐ธ
If you invoke gcov with multiple input files, the contributions from each input file 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 contain the : separated fields along with the program source code. The format is:
<execution_count>:<line_number>:<source line text>
Additional block information may follow each line, if you ask for it with a command line option. The execution_count is - for lines that contain no code. Unexecuted lines are marked ##### or =====, depending on whether they're reachable by non-exceptional paths or only by exceptional paths (like C++ exception handlers), respectively. With the -a option, unexecuted blocks are marked $$$$$ or %%%%%, depending on whether a 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 ๐ This functionality is not supported in Ada.
Note that GCC can completely remove the bodies of functions that aren't needed, like if they're inlined everywhere ๐ป Those functions get marked with -, which can be super confusing. To keep them around and let gcov properly show their execution_count, use the -fkeep-inline-functions and -fkeep-static-functions options ๐ฅ
Some lines of info 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 --- do not rely on them remaining unchanged. Use tag to locate a particular preamble line ๐
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 gcov prints percentages, 0% and 100% only show up when the values are exactly 0% and 100% ๐ Anything that would normally get rounded to 0% or 100% gets printed as the nearest non-boundary value instead. Not gonna lie, that's a very principled little rule โจ
When using gcov, you first have to compile your program with a special GCC option, --coverage. This tells the compiler to generate the extra information gcov needs (basically a flow graph of the program), and it also adds some extra code to the object files for generating the profiling information gcov needs. These additional files get placed in the directory where the object file is located ๐๏ธ
Running the program will cause profile output to be generated. 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 will now produce a listing of the code along with how often each line runs. For example, if your program is called tmp.cpp, this is what you'd see when using 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 contains output from gcov. Here is a sample, and it's giving chaotic but useful ๐
-: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:}
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, so the other lines don't show as containing code unless earlier blocks end on them. The total execution count of a line gets shown, and the lines after it show counts for each individual block that ends there. After each block, you also get its branch and call counts if you pass -b โจ.
Because of the way GCC instruments calls, a call count can pop up after a line with no individual blocks ๐. Check out line 33 in the example below, which has a basic block that was never 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, you get a line showing how many times it was called, how many times it returned, and what percentage of its blocks got executed ๐.
For each basic block, a line gets printed after the last line of that block, describing the branch or call that ends it. One source line can have several branches and calls listed if multiple basic blocks end there, and each one gets a number ๐ข. There's no simple way to map those back to source constructs, but generally 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. Otherwise you'll see the message "never executed" ๐ญ.
For a call, if it ran at least once, you get a percentage of how often it returned divided by how often it was executed. This is usually 100%, but it can be lower for functions that call exit or longjmp, since those might not return every time they're called ๐.
The execution counts are cumulative ๐. If you run the example program again without deleting the .gcda file, the counts for each line get added onto the results from the previous run(s). That's super useful for accumulating data over a bunch of program runs as part of a test verification suite, or for getting 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 the file doesn't match the executable (differing number of basic block counts), it ignores the contents of that file. Then it adds in the new execution counts and finally writes the data 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 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, don't compile with optimization at the same time ๐ซ. On some machines the optimizer can eliminate 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 that case there's no way for gcov to calculate separate execution counts for each line, because there isn't separate code for each line ๐ต. So if you compiled 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, executed 100 times. In one sense that's correct, because there was only one instruction representing all four of these lines. But 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 is inlined, or whether it isn't inlined at all.
If the function isn't 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 ๐ค. 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 now be calculable at compile time in some instances ๐ง . Because the coverage of all the uses of the inline function is 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) clears all profile counters to zero, and calling __gcov_dump(void) dumps the profile information collected at that point to .gcda output files ๐. Instrumented applications use a static destructor with priority 99 to invoke the __gcov_dump function. So __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 via dlopen functionality, -Wl,--dynamic-list-data is needed to dump all profile data ๐.
The profiling run-time library reports various errors related to profile manipulation and profile saving ๐จ. Errors are printed into standard error output, or into the GCOV_ERROR_FILE file if that environment variable is used. 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-2021 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 ๐. With the Invariant Sections being "GNU General Public License" and "Funding Free Software", the Front-Cover texts being (a) (see below), and the Back-Cover Texts being (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.
And that's the whole page, bestie ๐ซถ You're officially dangerous with gcov now ๐ . This one's from gcc-11.5.0, dated 2024-07-19 ๐ธ. Go be a main character! ๐
๐ฆ where this page comes from
- ubuntu noble: gcc-11-hppa-linux-gnu 11.5.0-1ubuntu1~24.04cross1
- ubuntu questing: gcc-11-hppa-linux-gnu 11.5.0-7ubuntu1cross1
- ubuntu resolute: gcc-11-hppa-linux-gnu 11.5.0-11ubuntu2cross1
- ubuntu stonking: gcc-11-hppa-linux-gnu 11.5.0-11ubuntu2cross1
- ๐ girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms