0

I run the following code with gcovr, and get 100% line-coverage, despite bar not being called. What am I doing wrong?

#include <iostream>

struct A{
    static void foo(){
        std::cout << "foo" << std::endl;
    }

    static void bar(){
        std::cout << "bar" << std::endl;
    }
};

int main() {
    A::foo();
    // A::bar();
}

The HTML report looks like this: enter image description here

I use the following CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

set(PROJECT_NAME test_gcovr)
project(${PROJECT_NAME})

if(NOT CMAKE_COMPILER_IS_GNUCXX)
    message("must use gnu compiler")
    EXIT()
endif()

set(CMAKE_CXX_FLAGS "-g -Wall -O0")

add_executable(run_tests ${PROJECT_SOURCE_DIR}/test.cpp)

set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/CMakeModules)
include(CodeCoverage)
append_coverage_compiler_flags()

setup_target_for_coverage_gcovr_html(NAME run_tests_coverage
                                    EXECUTABLE run_tests
                                    DEPENDENCIES run_tests)

With this CodeCoverage.cmake.

I compile and run with a call to cmake, followed by make run_tests_coverage.


EDIT: It appears that in the example above, bar is not part of the executable, despite -O0... I fixed this with:

...
bool x = false;
if (x){
    A::bar();
};
...

and now I get a correct coverage report.

Now the question remains - how to check coverage of tests for header-only libraries (without going through the report in detail)?


EDIT #2:

see this Getting useful GCov results for header-only libraries

Benny K
  • 868
  • 6
  • 18
  • 1
    I wonder whether the `bar()` function was already removed by the compiler because it is obvious that it can never be called. Can you check that (for example using `nm`)? – Daniel Junglas Aug 13 '20 at 08:57
  • You are correct (I thought I checked for this earlier, but the compiler appears to be smarter than I expected). See edit. – Benny K Aug 13 '20 at 09:12
  • 1
    This seems a similar question: https://stackoverflow.com/questions/9666800/getting-useful-gcov-results-for-header-only-libraries I guess you will have to find a way to force the compiler to emit unused inline functions into the code. – Daniel Junglas Aug 13 '20 at 09:14
  • Apparently, there some (hidden?) options like `--keep-static-functions` and `--keep-inline-functions`. I found them mentioned here: https://patchwork.ozlabs.org/project/gcc/patch/22f49725f56049abf9bf99edd7e79728b180fad1.1509005504.git.mliska@suse.cz/ Maybe those flags can make the unused functions show up? – Daniel Junglas Aug 13 '20 at 09:52
  • @DanielJunglas I already deleted the minimal example, but in my original project (with googletest) these options cause a linker error :( . The no-inline flags mentioned [here](https://stackoverflow.com/questions/9666800/getting-useful-gcov-results-for-header-only-libraries) also don't help. – Benny K Aug 13 '20 at 10:56

0 Answers0