How to use gcov with Cmake

fedest picture fedest · Jun 22, 2016 · Viewed 9.3k times · Source

I'm having difficulties following this guide (that I've seen recommended on another post) on the matter https://github.com/bilke/cmake-modules/blob/master/CodeCoverage.cmake

First:

Copy this file into your cmake modules path.

How do I know what my cmake module path is?

Use the function SETUP_TARGET_FOR_COVERAGE to create a custom make target

What does it mean exactly? How do I do that? Especifically, what do I have to type and where?

I am forced to compile the application with cmake, otherwise I would do it with gcc.

Answer

galsh83 picture galsh83 · Jun 22, 2016

You set the cmake module path by calling set(CMAKE_MODULE_PATH <path>)

The cmake module path setting tells cmake where to look for cmake modules like those that are included by the include macro.

For example, the steps I took to use CodeCoverage.cmake are:

  1. Copy CodeCoverage.cmake into my source folder at 'scripts/cmake'.
  2. Add the following to my CMakeLists.txt:

    set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/scripts/cmake)
    
    if (CMAKE_BUILD_TYPE STREQUAL "Coverage")
        include(CodeCoverage)
        setup_target_for_coverage(${PROJECT_NAME}_coverage ${TEST_TARGET} coverage)
    
        SET(CMAKE_CXX_FLAGS "-g -O0 -fprofile-arcs -ftest-coverage")
        SET(CMAKE_C_FLAGS "-g -O0 -fprofile-arcs -ftest-coverage")
    endif() #CMAKE_BUILD_TYPE STREQUAL "Coverage"
    
  3. Run cmake with -DCMAKE_BUILD_TYPE=Coverage

  4. Run make

  5. Run make <coverage_target>

Note that:

  • ${TEST_TARGET} is a variable I set with the name of my unit testing target that I create earlier in the script.
  • <coverage_target> is whatever string that is generated by ${PROJECT_NAME}_coverage.
  • You don't have to wrap the coverage creation with the if like I did.
  • Since I'm using AppleClang, I had to fix the CodeCoverage.cmake script to allow it. The way it is written now allows gcc and clang 3.0.0 or newer only.