Generating a coverage report with GCC

If your code contains unit tests that use the assert header of the standard libraries, you can also get coverage information using the gcov test code coverage analysis tool of GCC. Consider a simple C++ program named cover.cpp with the content displayed below.

#include <cassert>

int max(int a, int b) {
    if (a > b) {
        return a;
    }
    return b;
}

int main() {
    assert(max(1, 0) == 1);
    return 0;
}

Compile the program the --coverage flag.

g++ --coverage cover.cpp -o cover

After the compilation the content of the directory are the following.

$ ls
cover  cover.cpp  cover.gcno

Run the cover executable.

./cover

After the executable was run the file cover.gcda was added in the directory.

$ ls
cover  cover.cpp  cover.gcda  cover.gcno

You can now call gcov to get the coverage information.

$ gcov cover
File 'cover.cpp'
Lines executed:85.71% of 7
Creating 'cover.cpp.gcov'

Lines executed:85.71% of 7

For instance in this case you can increase the coverage by testing one more execution path.

#include <cassert>

int max(int a, int b) {
    if (a > b) {
        return a;
    }
    return b;
}

int main() {
    assert(max(1, 0) == 1);
    assert(max(1, 2) == 2);
    return 0;
}

With the additional assertion max(1, 2) == 2, the coverage report is the following.

$ gcov cover
File 'cover.cpp'
Lines executed:100.00% of 8
Creating 'cover.cpp.gcov'

Lines executed:100.00% of 8