NoSenseEtAl
NoSenseEtAl

Reputation: 30128

c++ coverage setup with CMake

I have CMake project that sometimes may use clang, sometimes it may use gcc, sometimes it may use MSVC. Does CMake provide some generic way to enable coverage generation, or do I need to do if else by myself(compiler flags for gcc and clang differ, and MSVC does not have coverage)?

Upvotes: 3

Views: 1714

Answers (1)

lubgr
lubgr

Reputation: 38315

There is no central cmake option to handle such a situation, but some solutions could be:

  • Don't do anything. Collect coverage statistics with kcov, which doesn't require special compiler flags.
  • Add a build configuration alongside the usual Debug, RelWithDebugInfo and so on. Then, select this build configuration only when it makes sense, i.e., when compiling with clang or gcc. Like this:

    set(CMAKE_BUILD_TYPE "${CMAKE_BUILD_TYPE}" CACHE STRING
        "Build options: None Debug Release RelWithDebInfo MinSizeRel Coverage." FORCE)
    
    # Use generator expression to enable flags for the Coverage profile
    target_compile_options(yourExec
        $<$<CONFIG:COVERAGE>:--coverage>)
    
    # Don't forget that the linker needs a flag, too:
    target_link_libraries(yourExec
        PRIVATE $<$<CONFIG:COVERAGE>:--coverage>)
    

    When you need to dispatch further on the compiler type, you can use generator expressions, too.

    $<$<OR:$<CXX_COMPILER_ID:AppleClang>,
        $<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:GNU>>:-someOtherFlag>
    

    but as far as I know, there are no real differences between clang and gcc with respect to coverage flags.

  • Don't add another build configuration, just define the above flags for the build configuration you intend to use for coverage reports, probably Debug. Then, it's obviously necessary to exclude MSVC.

    target_compile_options(yourExec
        $<$<AND:$<CONFIG:DEBUG>,$<NOT:CXX_COMPILER_ID:MSVC>>:--coverage>)
    
    target_link_libraries(yourExec
        PRIVATE $<$<AND:$<CONFIG:DEBUG>,$<NOT:CXX_COMPILER_ID:MSVC>>:--coverage>)
    

Upvotes: 2

Related Questions