сряда, 22 януари 2014 г.

Code coverage with GCC, gcov and lcov

Want to see some code coverage in your C/C++ project. If you are going with gcc/g++ it is very easy. All you need is the GNU toolchain of course and lcov utility. The lcov utility is wrapper around another GNU tool: gcov. Let's see how it works.
Here is vary small c++ project with just 2 source and 1 header file:

main.cpp:
#include <iostream>
#include "testclass.h"
using namespace std;
void local1()
{
        cout << "local1()" << endl;
}
void local2()
{
        cout << "local2()" << endl;
}
int main()
{
        TestClass tc;
        tc.hello();
}
testclass.cpp:
#include <iostream>
#include "testclass.h"
using namespace std;
TestClass::TestClass()
{
        cout << "TestClass::TestClass()" << endl;

}
void TestClass::hello()
{
        cout << "TestClass::hello()" << endl;
}
testclass.h:
class TestClass
{
        public:
                TestClass();
                void hello();
};
makefile:

CPP=g++
CPPFLAGS=-c -Wall --coverage
LDFLAGS=--coverage
SRCS=main.cpp testclass.cpp
OBJS=$(SRCS:.cpp=.o)
EXEC=test

ALL: $(SRCS) $(EXEC)
       
$(EXEC): $(OBJS)
        $(CPP) $(LDFLAGS) $(OBJS) -o $@
.cpp.o:
        $(CPP) $(CPPFLAGS) $< -o $@
clean:
        rm -f $(EXEC)
        rm -f *.o

In order to collect coverage data, you need to compile and link source and object files with --coverage option.  Have a look at the makefile!
Data is analyzed by lcov utility:

$lcov -t "Coverage test" -o coverage.info -c -d .
And output is produced by genhtml tool:

$genhtml -o results coverage.info

Now you can go to "results" folder and enjoy the colorful output! Just open index.html and have fun:





Няма коментари:

Публикуване на коментар