Why two compiler flags needs to be passed for code coverage in GCC

ccode-coveragegccgcov

I understand two compiler flags: -ftest-coverage -fprofile-arcs needs to be passed for getting code coverage in GCC.
My question is, what is the reasoning for having 2 compiler flags for getting coverage. Also, what can we get if we use them independently?.

I tried compiling a c program with only -fprofile-arcs flag. I didnt notice any differences. Was able to generate .gcno .gcda and gcov files

Best Answer

If you want to use the Gcov tool to get code coverage in GCC, refer to this documentation which explicitly states:

When using gcov, you must first compile your program with two special GCC options: ‘-fprofile-arcs -ftest-coverage’. This tells the compiler to generate additional information needed by gcov (basically a flow graph of the program) and also includes additional code in the object files for generating the extra profiling information needed by gcov.

More precisely, by referring to the Instrumentation Options, my understanding about the two flags is the following:

  • -fprofile-arcs generates the information indicating how many times each branch of your program is taken; in other words, this makes your program generate extra data relative to its execution. The information is stored into .gcda files.
  • -ftest-coverage uses the information produced by -fprofile-arcs, and generates .gcno files containing control flow information, which can be used by Gcov to produce human readable .gcov files. Without the test coverage data obtained with -fprofile-arcs, you will not get anything meaningful.

The -fprofile-arcs can also be combined with other flags, such as -fbranch-probabilities (more information here). Typically when using this flag, the compiler performs optimisations to improve branch prediction based on the profiling information contained in the .gcda files. -fprofile-arcs and -fbranch-probabilities are automatically enabled when using -fprofile-generate and -fprofile-use (this is the standard way for performing Profile-Guided Optimisation with GCC).

Hope this helps!

Related Topic