Search code examples
c++gcov

how to get per test coverage for google tests c++ with gcov


I would like to get per test coverage for every test case in my c++ program.

What I get is that GoogleTest allows some actions to be performed before and after every test

#pragma once
#include <gtest/gtest.h>
#include <gcov.h>
class CodeCoverageListener : public ::testing::TestEventListener
{
public:
    virtual void OnTestProgramStart(const ::testing::UnitTest&) {}
    virtual void OnTestIterationStart(const ::testing::UnitTest&, int) {}
    virtual void OnEnvironmentsSetUpStart(const ::testing::UnitTest&) {}
    virtual void OnEnvironmentsSetUpEnd(const ::testing::UnitTest&) {}
    virtual void OnTestCaseStart(const ::testing::TestCase&) {}
    virtual void OnTestPartResult(const ::testing::TestPartResult&) {}
    virtual void OnTestCaseEnd(const ::testing::TestCase&) {}
    virtual void OnEnvironmentsTearDownStart(const ::testing::UnitTest&) {}
    virtual void OnEnvironmentsTearDownEnd(const ::testing::UnitTest&) {}
    virtual void OnTestIterationEnd(const ::testing::UnitTest&, int) {}
    virtual void OnTestProgramEnd(const ::testing::UnitTest&) {}

    virtual void OnTestStart(const ::testing::TestInfo& test_info)
    {
        __gcov_reset();
    }

    virtual void OnTestEnd(const ::testing::TestInfo& test_info)
    {
       __gcov_dump();
    }
};

And then you tell GoogleTest about this

 ::testing::UnitTest::GetInstance()->listeners()
        .Append(new CodeCoverageListener);

But during compilation with gcc4.8.5 I get error:

 fatal error: gcov.h: No such file or directory
 #include <gcov.h>

How to tell gcc where to look for this include?

During compilation with gcc8.4.1 I get linker error:

 g++ -lgcov gcov.cpp
/tmp/ccK7o95R.o: In function `main':
gcov.cpp:(.text+0x5): undefined reference to `__gcov_reset()'
collect2: error: ld returned 1 exit status

How to link gcov to c++ program?


Solution

  • The gcov.h header is internal to GCC, so it is not installed in any include path. If you want to call the gcov functions yourself (which I don't recommend), then you would have to declare them yourself.

    extern void __gcov_reset (void);
    extern void __gcov_dump (void);
    

    Linking with libgcov should work, with the caveat that it is a static library.