How to do code coverage in cmake

Monku picture Monku · Jun 10, 2015 · Viewed 15.9k times · Source

I want to use code coverage tools(lcov) in my cmake project. I read the example here https://github.com/bilke/cmake-modules/blob/master/CodeCoverage.cmake The tests are added in my project using the 'add_test()' cmake function.

I want to create a custom target, something called 'test_coverage', that when invoked for execution should run all the tests, collect their coverage data and generate the html(using genhtml) in a directory 'code_coverage'.

Is there a way I could get the list of all the tests in my project and their directory paths, so that in the custom target 'test_coverage' I could execute each test individually and collect its coverage data ?

Answer

jerrylogansquare picture jerrylogansquare · Aug 17, 2017

You can either execute 'ctest -VV' from the command line, and if all tests were created using add_test, all will execute.

If you want a custom build target to do the same, you can use this code:

add_custom_target(run_tests
   COMMAND "ctest -VV" )

I have a LOT of cmake code for code coverage and unit testing to show, but it doesn't make sense to copy/paste here yet since it sounds like you're just getting started.