Adding Code Coverage to your C++ project

For that example, I'll use one of my GitHub project arduino-toolbox, Travis-CI and Coveralls but the commands lines will be exactly the same for any other setup.

Since the project is using Cmake, the following commands could go inside an add_custom_target  rule in CMakeLists.txt

Adding C++ coverage flag

Add --coverage  to your CFLAGS or CXXFLAGS.

With CMake for C++, it gives you:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0") # debug, no optimisation
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --coverage") # enabling coverage

Replace CMAKE_CXX_FLAGS  by CMAKE_C_FLAGS  for a C project.

Nothing more is needed. From the GNU GCC man:

--coverage

This option is used to compile and link code instrumented for coverage analysis. The option is a synonym for -fprofile-arcs -ftest-coverage (when compiling) and -lgcov (when linking).

 

The Travis-CI configuration

At the root of your git repository, in .travis.yml :

install:
- cd ${TRAVIS_BUILD_DIR}
# install latest LCOV (1.9 was failing for me) [1]
- wget http://ftp.de.debian.org/debian/pool/main/l/lcov/lcov_1.11.orig.tar.gz
- tar xf lcov_1.11.orig.tar.gz
- sudo make -C lcov-1.11/ install
# install lcov to coveralls conversion + upload tool
- gem install coveralls-lcov

before_script: (optional: for paranoiacs only)
- cd ${TRAVIS_BUILD_DIR}
- lcov --directory . --zerocounters

script:
- cd ${TRAVIS_BUILD_DIR}
- <your command that compiles> # will generate *.gcno files
- <your command that runs> # will generate *.gcda files

after_success:
- cd ${TRAVIS_BUILD_DIR}
- lcov --directory . --capture --output-file coverage.info # capture coverage info
- lcov --remove coverage.info 'tests/*' '/usr/*' --output-file coverage.info # filter out system and test code
- lcov --list coverage.info # debug before upload
- coveralls-lcov --repo-token ${COVERALLS_TOKEN} coverage.info # uploads to coveralls

My full .travis.yml  with support for GTest/GMock and GCC C++11 enable compiler is here.

The value of the environment variable ${COVERALLS_TOKEN}  is set in the settings page of your Travis project (https://travis-ci.org/<github-user>/<project-name>/settings) under the 'Environment Variables' section.

Notes

[1]: this should be not needed when travis VM image will update to Ubuntu Utopia.

 


Update: 13/01/2016

As mentioned in the comment and here, you SHOULD not specify your repo-token on the command line.

3 thoughts on “Adding Code Coverage to your C++ project

  1. coveralls-lcov --repo-token coverage.info

    You must NOT specify a repo-token if you're uploading from a public repository using travis-ci.org

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.