在运行时禁用gcov覆盖

disable gcov coverage at run-time

本文关键字:gcov 覆盖 运行时      更新时间:2023-10-16

我正在用c++编写一些测试,我正在使用gcov(实际上是lcov,但我认为这是无关紧要的)来获取有关覆盖率的信息。

有没有办法在运行时禁用信息记录?如:

bool myTest() {
    ObjectToTest obj;
    /* Enable gcov... */
    obj.FunctionToTest();
    /* ...Disable gcov */
    if(obj.GetStatus() != WHATEVER)
        return false;
    else
        return true;
}

在这种情况下,我希望gcov显示为"覆盖"只是FunctionToTest,但留下ObjectToTest构造函数和GetStatus"未覆盖"。

提前感谢!

不,如果发生gcov,我们没有这样的选择。

我在一些覆盖工具中看到过这样的选项,比如clover,它通过直接检测源代码来工作。

你的问题的一个解决方案将是把这部分代码写到一个不同的源文件,然后在你想要的源文件中调用它。
我之所以建议这样做,是因为当您稍后使用LCOV或GCOVR生成覆盖率报告时,它们都提供了通过将指定文件传递给某些开关来从覆盖率报告中排除指定文件的选项。

LCOV:

-r tracefile pattern
   --remove tracefile pattern
          Remove data from tracefile.

GCOVR:

-e EXCLUDE, --exclude=EXCLUDE
                    Exclude data files that match this regular expression

虽然我同意@VikasTawniya所说的,但是您也可以在测试代码中模拟您不喜欢跟踪的函数。

 #ifdev NO_COV
 #include mock.h // mock of obj.FunctionToTest(); does nothing
 #else 
 #include real.h // real implementation of obj.FunctionToTest();
 #endif

现在你的承保结果不会因为obj.FunctionToTest()的呼叫而受到影响

现在可行的解决方案(2023),

void some_function() {
  __gcov_reset(); // this will reset all profile counters
  do_something();
  __gcov_flush(); // this will flush all counters (note: this flush is incremental and will not overwrite existing profile data)
}
// To prevent other parts of profile data from being flushed
void __attribute__((destructor)) clear_redundant_gcov() {
  __gcov_reset();
}

附加说明:当你用gcov编译源代码时,gcc会插入很多API调用(例如__gcov_inc_counter(xxx),只是一个例子),并且可以在你的源代码中调用这些gcov API调用。