C/C++: gcov and lcov
Monday, 11 July 2011 20:39

Below are some notes on how to use the 'gcov' and 'lcov' test coverage programs.

gcov

'gcov' is easy to use, however it produces lots of files even for a simple program.

  • Add the following options to your compile and linker commands '-fprofile-arcs -ftest-coverage'
    • g++ -O0 -g3 -Wall -c -fprofile-arcs -ftest-coverage -o main.o ./main.cpp
    • g++ -fprofile-arcs -ftest-coverage -o avltree ./main.o
  • After building main.cpp you will see the below file created:
    • main.gcno
  • After running your recompiled executable files like below will be created:
    • main.gcda
  • Now produce your coverage results
    • gcov main.cpp
    • 		File '../main.cpp'
      		Lines executed:76.00% of 250
      		../main.cpp:creating 'main.cpp.gcov'
      
      		...
      
      		File '../avltree.h'
      		Lines executed:89.41% of 236
      		../avltree.h:creating 'avltree.h.gcov'
      
      		...
      
      		File '../treenode.h'
      		Lines executed:100.00% of 45
      		../treenode.h:creating 'treenode.h.gcov'
      
      		...
      		
  • Now view the coverage report
    • more avltree.h.gcov
    • 			...
      			...
      		        -:  206:template
      		  3091570:  207:treenode * avltree::rotateLeft(treenode * subtree) {
      		  3091570:  208:	treenode * pivot = NULL;
      		        -:  209:
      		  3091570:  210:	pivot = subtree->getRight();
      		  3091570:  211:	subtree->setRight(pivot->getLeft());
      		  3091570:  212:	pivot->setLeft(subtree);
      		        -:  213:
      		  3091570:  214:	subtree->updateHeight();
      		  3091570:  215:	pivot->updateHeight();
      		        -:  216:
      		  3091570:  217:	return pivot;
      		        -:  218:}
      		        -:  219:
      			...
      			...
      		
  • lcov

    'lcov' is a graphical front end for 'gcov' that produces a great html summary of your test coverage.

    Along with the summary a report of exercised lines of code (blue), and untested code (orange) is produced.

    An example run of 'lcov' is below.

    • Initialize the directory where you wish to store the 'html' result in:
      • mkdir lcovdir
      • cd lcovdir
      • lcov --directory ../ --zerocounters
    • Run the test application:
      • ../avltree
    • Process the results into a single file:
      • lcov --directory ../ --capture --output-file app.info
    • Generate the html results and view them
      • genhtml -o . app.info
      • firefox ./index.html