How to Perform C Code Coverage Testing with gcov and lcov on Ubuntu
This article explains how to set up gcov and lcov on Ubuntu, write a simple C++ program, compile it with coverage flags, generate .gcno and .gcda files, use lcov to create an HTML coverage report, and interpret the resulting line and function coverage percentages.
Background : In recommendation system testing, code coverage is a key metric for assessing test completeness, especially for C code. This guide shows how to measure C code coverage using gcov and lcov on Ubuntu.
Environment preparation : Install the required tools on Ubuntu:
sudo apt-get install gcov sudo apt-get install lcovVerify installation with gcov -v and lcov -v .
Simple example : Write a basic C++ program (shown in the original images) and compile it with coverage flags -ftest-coverage and -fprofile-arcs . After compilation, the presence of test.gcno indicates successful instrumentation.
Generating the executable : Link the object files to produce the binary. Running the binary creates .gcda files, which contain execution counts for each line.
Generating test results : Use lcov to capture coverage data and produce an HTML report:
lcov -c -d . -o coverage.info genhtml coverage.info -o coverage_reportThe HTML report visualizes covered (blue) and uncovered (red) lines, showing execution counts and highlighting missed lines with ##### .
Coverage metrics : The report displays line coverage (e.g., 53.8%) and function coverage (e.g., 40.00%), including the main function.
Conclusion : This tutorial demonstrated basic C code coverage testing with gcov and lcov. Future posts will cover coverage for shared libraries and external parameters. Stay tuned for more testing insights.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.