'How to calculate the code coverage of testcases that coresponding to C program using gcov?

The C program comprises a .c and .h files.

When the C program compiles and runs, it asks command line input(the program continues ask for input until user enter "bye" and click enter).

The testcases includes lots of .in and .out format files.

The .in file is the input of command line,.out file is the output of the program.

I have the .sh file that runs the .in format file and compare output with .out format file.My test cases(.in,.out files) are in a folder called "tests".

I found the argument that use in gcov can't use the .sh format file.

I wonder how to calculate the code coverage of my testcases and find which lines of code are not covered by my testcases?



Solution 1:[1]

You can add test coverage simply:

  1. In your compilation option, add -fprofile-arcs -ftest-coverage. That way, the produced executable program produce statistics each times it is called (in .gcno / .gcda files).

  2. Execute you .sh test file

  3. Ask gcov to generate statistics files: type gcov -m *.c, that will produce .c.gcov files containing the coverage test results.

For instance, We can create the following program and test it.

#include <stdio.h>

int main(int argc) 
{
    if (argc) {
        printf("not zero");
    } else {
        printf("zero"); 
    }
    return 0;
}
gcov -m *.c
File 'foo.c'
Lines executed:80.00% of 5
Creating 'foo.c.gcov'

The result file will be:

        -:    0:Source:foo.c
        -:    0:Graph:foo.gcno
        -:    0:Data:foo.gcda
        -:    0:Runs:1
        -:    0:Programs:1
        -:    1:#include <stdio.h>
        -:    2:
        1:    3:int main(int argc) 
        -:    4:{
        1:    5:    if (argc) {
        1:    6:        printf("not zero");
        -:    7:    } else {
    #####:    8:        printf("zero");
        -:    9:    }
        1:   10:    return 0;
        -:   11:}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mathieu