Fundamentals 4 min read

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.

360 Quality & Efficiency
360 Quality & Efficiency
360 Quality & Efficiency
How to Perform C Code Coverage Testing with gcov and lcov on Ubuntu

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 lcov

Verify 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_report

The 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

code coverageSoftware TestingCgcovlcovUbuntu
360 Quality & Efficiency
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.