Ramblings of a code junkie

November 12, 2006

Code coverage and profiling in C++

Written by

GCC comes with quite a lot of handy tools. Among many other tools it also provides code coverage and profiling tools for C and C++; ‘gcov’ is the code coverage checker.

When you want to see how much of your code is tested with your unit tests you can add the ‘-fprofile-arcs -ftest-coverage’ flags to CFLAGS or CXXFLAGS and run the resulting binary. The code will be instrumented and will result in a file being created at compile time ‘[source].gcno’ and one at run time ‘[source].gcda’. These files contain the coverage and profiling information.

You can then run gcov on the source file and see how many lines / branches (depending on command line options) you covered.

An example:

$ gcc -fprofile-arcs -ftest-coverage tmp.c
$ a.out
$ gcov tmp.c
90.00% of 10 source lines executed in file tmp.c
Creating tmp.c.gcov.

In order to do profiling as well you need to add ‘-pg’ to CFLAGS / CXXFLAGS. After running the resulting executable you will see that a file called gmon.out is generated. Now you can run ‘gprof [executable name]’ and see where your code spends its time.

Zarro Taags!

2 comments for this post.

  1. Comment from Ranjith on December 10th, 2006 :


    Will you give any examples which works with c++ files.

  2. Comment from core on December 11th, 2006 :

    Hi Ranjith,

    For C++ it is exactly the same. In a C++ project of mine I have this in the Makefile’s:

    test_CXXFLAGS=-fprofile-arcs -ftest-coverage -pg
    test_CFLAGS=-fprofile-arcs -ftest-coverage -pg
    test_LDFLAGS=-g -fprofile-arcs -ftest-coverage -pg

    All the other commands, as described in the post work exactly the same.

Leave a Comment