Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ coverage setup with CMake

Tags:

c++

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)?

like image 385
NoSenseEtAl Avatar asked Dec 09 '25 19:12

NoSenseEtAl


1 Answers

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>)
    
like image 120
lubgr Avatar answered Dec 11 '25 08:12

lubgr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!