ges134
ges134

Reputation: 33

How to get coverage for tests with CMake and Catch2

I'm trying to print coverage with lcov on a C++ project that is using Catch2 for tests. I'm able to run my tests and get results. However, I'm unable to get any coverage. This is the error that is shown.

Capturing coverage data from .
Found gcov version: 9.3.0
Using intermediate gcov format
Scanning . for .gcda files ...
geninfo: WARNING: no .gcda files found in . - skipping!
Finished .info-file creation
Combining tracefiles.
Reading tracefile coverage.base
lcov: ERROR: no valid records found in tracefile coverage.base

My current toolchain is WSL. I'm using Conan for dependency management. The solution has the following structure:

my project/
├─ build/
│  ├─ build files
├─ core/
│  ├─ library files
├─ main/
│  ├─ main runtime
├─ tests/
│  ├─ test runtime/
├─ CMakeLists.txt

Each folder has it's CMakeLists.txt file and is identified as a target. I'm also using this CMake Module to register a target for coverage.

My root CMakeLists.txt looks like this:

cmake_minimum_required(VERSION 3.16)
project(my-project)

set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_FLAGS "-O0")

include(build/conanbuildinfo.cmake)
conan_basic_setup()

add_subdirectory(core)

option(BUILD_TESTING "Builds only the test executable." OFF)
option(CODE_COVERAGE "Collect coverage from test library" OFF)

if(BUILD_TESTING)
    enable_testing()
    add_subdirectory(tests)
    add_test(NAME project-tests COMMAND ./bin/tests)

    if(CODE_COVERAGE)
        include(CodeCoverage.cmake)
        append_coverage_compiler_flags()
        setup_target_for_coverage_lcov(NAME coverage EXECUTABLE ./bin/tests BASE_DIRECTORY ../coverage)
    endif()
else()
    add_subdirectory(main)
endif()

To get my coverage, I'm using the following commands (on build/).

cmake .. -DCODE_COVERAGE=ON -DBUILD_TESTING=ON -DCMAKE_BUILD_TYPE=Debug
make
make coverage

From what I understand, it seems to be missing some files necessary for coverage information, but I don't know how to make them. From what I've looked online, I have all the necessary compiler flags. I can't see what is wrong/missing in here.

Upvotes: 3

Views: 4965

Answers (1)

Anton Artiukh
Anton Artiukh

Reputation: 106

I believe you forgot to add appropriate flags

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage")
set(CMAKE_CXX_FLAGS " ${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage")

Upvotes: 2

Related Questions