Install lcov on Ubuntu 26.04

Install lcov on Ubuntu 26.04

The lcov is a command-line tool designed to collect and present code coverage information generated by GCC. It works with coverage data produced by GCC instrumentation features and provides a brief summary of executed lines and functions. This tutorial explains how to install lcov on Ubuntu 26.04.

Prepare environment

GCC is required to compile a program with coverage instrumentation. Install the compiler package with:

sudo apt install -y gcc

Install lcov

Run the following command to update the package lists:

sudo apt update

Install lcov with:

sudo apt install -y lcov

Verify that lcov has been installed successfully by checking its version:

lcov --version

Testing lcov

A small C program is used to demonstrate coverage generation. Create a source file:

nano main.c

Insert the following code:

int is_positive(int x) {
    if (x > 0) {
        return 1;
    }

    return 0;
}

int main(void) {
    is_positive(1);

    return 0;
}

Compile the application with GCC coverage instrumentation enabled by using the --coverage option. To make the generated coverage data easier to analyze, optimizations are disabled and debug information is enabled.

gcc --coverage -g -O0 main.c -o test

Once compilation is complete, GCC generates an additional file such as test-main.gcno. This file contains coverage metadata required for collecting and processing execution results.

Run the resulting executable to generate runtime coverage data:

./test

After the executable completes, GCC creates a runtime coverage file such as test-main.gcda. The .gcda and .gcno files are used together by lcov to calculate the coverage results.

Use lcov to capture the coverage information from the current directory and save it to coverage.info:

lcov --capture --directory . --output-file coverage.info

The resulting coverage file can be inspected using the --list option:

lcov --list coverage.info

The command displays a summary containing line and function coverage:

            |Lines       |Functions  
Filename    |Rate     Num|Rate    Num
=====================================
/main.c     |85.7%      7| 100%     2
=====================================
      Total:|85.7%      7| 100%     2
Message summary:
  no messages were reported

Uninstall lcov

If lcov is no longer needed, remove the package and its automatically installed dependencies with:

sudo apt purge --autoremove -y lcov

Leave a Comment

Cancel reply

Your email address will not be published.