gcov is a tool for measuring code coverage in C and C++ programs. It is based on the GCC (GNU Compiler Collection) and works by instrumenting the binary code generated by GCC, in order to collect data on how many times each line of code is executed at runtime. This data is then used to generate reports on the code coverage, highlighting which parts of the code have been tested and which have not.
When you build your program with GCC and the -fprofile-arcs -ftest-coverage options, GCC will generate extra information in the object files and executable, it will also link the program with the libgcov library, which contains the instrumentation code. When the program runs, it updates the information in the object files with the execution counts. Then, running gcov on the executable will process these files and generate a coverage report.
The report generated by gcov is a text file containing a copy of the source code, with each line preceded by a number indicating the number of times that line was executed. This allows developers to quickly identify which parts of the code are not being executed and may need more testing.
gcov also provides various options for customizing the output and filtering the data, such as:
- -b option: to include branch coverage information
- -l option: to include line coverage information
- -p option: to include information about individual functions.
gcov is a useful tool for discovering untested parts of a program and for identifying areas where testing can be improved. It can be used as part of a continuous integration process to check that new changes do not decrease the coverage. Additionally, it can also be used for performance optimization as by looking at the coverage data, you can spot the most frequently executed parts of the code and see if there are any inefficiencies there.
If you encounter the below error while running the command gcov:
gcov: command not found
you may try installing the below package as per your choice of distribution:
|Debian||apt-get install gcc|
|Ubuntu||apt-get install gcc|
|Alpine||apk add gcc|
|Arch Linux||pacman -S gcc|
|Kali Linux||apt-get install gcc|
|CentOS||yum install gcc|
|Fedora||dnf install gcc|
|OS X||brew install gcc|
|Raspbian||apt-get install gcc|
gcov Command Examples
1. Generate a coverage report named `file.cpp.gcov`:
# gcov path/to/file.cpp
2. Write individual execution counts for every basic block:
# gcov --all-blocks path/to/file.cpp
3. Write branch frequencies to the output file and print summary information to stdout as a percentage:
# gcov --branch-probabilities path/to/file.cpp
4. Write branch frequencies as the number of branches taken, rather than the percentage:
# gcov --branch-counts path/to/file.cpp
5. Do not create a `gcov` output file:
# gcov --no-output path/to/file.cpp
6. Write file level as well as function level summaries:
# gcov --function-summaries path/to/file.cpp