A template or inline function in a header file has no coverage

Problem

Sometimes Coco “forgets” code coverage for a C or C++ header file. Typically that happens when there are

After the test program has run and code coverage is measured, some coverage is missing. It belongs to a function defined in header files of the library that was clearly executed by the test program. But it is possible that other functions in the header file do have coverage.

Explanation

The usual cause of such a problem is that Coco was not involved in the compilation of the test program.

This is because Coco needs to instrument a function in a header file every time it encounters it. When Coco instruments a program, it intercepts calls to the compiler during the build process. A compiler call looks like this,

g++ myfile.cpp -o myfile.o

or something similar if the compiler is not g++. The compiler reads a source file (a file that ends with .c or .cpp), and Coco intercepts this call and modifies this file. How do the header files enter the picture? Coco actually operates on the preprocessed text of myfile.cpp, which contains all files it included via a “#include” statement, the files included by them, and so on. This file is then instrumented by Coco.

So when a header file contains inline functions or template code, this code is not just instrumented once, but many times, once for each source file that includes the header file. And Coco collects the data afterwards, so that you don’t need to care.

This explains what happens with a test program that is not processed by Coco: When a test calls a inline function that resides in a library header file, this function is not instrumented.

On the other hand, it is possible that the test program calls another function of the library that resides in a source file and calls the inline function from the header file. This time, code coverage is measured, because the source file belongs to the library, which is instrumented.

Solution

The test program must therefore be instrumented too. Afterwards, the code of the test programs should be excluded from instrumentation, to measure code coverage correctly. Usually this is simple: If the test programs are all in a directory /tests/, the only thing to do is to add “--cs-exclude-file-abs-wildcard=*/tests/” to the coverage options.