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:


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 latest LCOV (1.9 was failing for me) [1]
- wget
- 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)
- lcov --directory . --zerocounters

- <your command that compiles> # will generate *.gcno files
- <your command that runs> # will generate *.gcda files

- lcov --directory . --capture --output-file # capture coverage info
- lcov --remove 'tests/*' '/usr/*' --output-file # filter out system and test code
- lcov --list # debug before upload
- coveralls-lcov --repo-token ${COVERALLS_TOKEN} # 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 (<github-user>/<project-name>/settings) under the 'Environment Variables' section.


[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

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

Comments are closed.