c++ - 查找未执行的 C++ 代码行

标签 c++ c++11 macros g++ code-coverage

作为单元测试的一部分,我想确保测试的代码覆盖率。目的是在代码中的某处放置诸如 REQUIRE_TEST 宏之类的东西,并检查是否所有这些都被调用。

void foo(bool b) {
  if (b) {
    REQUIRE_TEST
    ...
  } else {
    REQUIRE_TEST
    ...
  }
}

void main() {
  foo(true);

  output_all_missed_REQUIRE_macros();
}

理想情况下,输出将包括源文件和宏行。

我最初的想法是让宏创建静态对象,这些静态对象会在某个映射中注册自己,然后检查是否所有这些对象都被调用了

#define REQUIRE_TEST \
        do { \
            static ___RequiredTest requiredTest(__func__, __FILE__, __LINE__);\
            (void)requiredTest;\
            ___RequiredTest::increaseCounter(__func__, __FILE__, __LINE__);\
        } while(false)

但是静态对象只在第一次调用代码时创建。因此,该映射仅包含也在下一行中计算的函数 - 未找到缺少的 REQUIRE_TEST 宏。 __attribute__((used)) 在这种情况下被忽略。

gcc 有一个很好的属性 __attribute__((constructor)),但显然选择在放置在这里时忽略它(跟随代码而不是静态对象)

struct teststruct { \
  __attribute__((constructor)) static void bla() {\
    ___RequiredTest::register(__func__, __FILE__, __LINE__); \
  } \
};\

以及对于

[]() __attribute__((constructor)) { \
  ___RequiredTest::register(__func__, __FILE__, __LINE__); \
};\

我现在能想到的唯一出路是 a) 手动(或通过脚本)分析常规编译之外的代码 (uargh) 或 b) 使用 __COUNTER__ 宏来计算宏- 但我不知道哪个特定的 REQUIRE_TEST 宏没有被调用......(如果其他人决定使用 __COUNTER__ 宏,一切都会中断......)

Are there any decent solutions to this problem? What am I missing? It would be nice to have a macro that appends the current line and file so some preprocessor variable whenever it is called - but that is not possible, right? Are there any other ways to register something to be executed before main() that can be done within a function body?

最佳答案

这个怎么样:

#include <iostream>

static size_t cover() { return 1; }

#define COV() do { static size_t cov[2] __attribute__((section("cov"))) = { __LINE__, cover() }; } while(0)

static void dump_cov()
{
        extern size_t __start_cov, __stop_cov;

        for (size_t* p = &__start_cov; p < &__stop_cov; p += 2)
        {
                std::cout << p[0] << ": " << p[1] << "\n";
        }
}

int main(int argc, char* argv[])
{
        COV();

        if (argc > 1)
                COV();

        if (argc > 2)
                COV();

        dump_cov();
        return 0;
}

结果:

$ ./cov_test
19: 1
22: 0
25: 0

和:

$ ./cov_test x
19: 1
22: 1
25: 0

和:

$ ./cov_test x y
19: 1
22: 1
25: 1

基本上,我们在命名的内存部分中设置了一个覆盖数组(显然我们为此使用了 GCC 特定的机制),我们在执行后将其转储。

我们依赖于在启动时执行的局部静态的持续初始化——将行号放入覆盖数组中,并将覆盖标志设置为零——并通过调用 cover() 进行初始化在第一次执行该语句时执行,它将已执行行的覆盖率标志设置为 1。我不是 100% 确定所有这些都由标准保证,也不是由标准的哪个版本保证(我使用 --std=c++11 编译)。

最后,使用“-O3”构建也能产生正确的结果(尽管以不同的顺序分配):

$ ./a
25: 0
22: 0
19: 1

和:

$ ./a x
25: 0
22: 1
19: 1

$ ./a x y
25: 1
22: 1
19: 1

关于c++ - 查找未执行的 C++ 代码行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29903391/

相关文章:

c++ - 基本类型的统一初始化语法?

c++ - 从线程中获得的 yield 远低于预期 - 为什么?

相同基础类型的 C++ 变体

c++ - 如何将 std::unique_ptr<T> 与返回 int 的接口(interface)一起使用?

C++ 条件变量和等待

c++ - 尝试使用 Visual Studio 2008 堆调试器调试内存泄漏

c - 结构访问代表文件名?

c++ - __COUNTER__ 宏是否可移植?

c++ - 从设备到主机的 Cuda Memcpy 崩溃

c++ - "printf("%s 行的内存漏洞应该是 %s", argv[1]);"被描述为堆栈溢出?