gtest –– 使用 TEST_F 时未定义的符号

gtest –– Undefined symbols when using TEST_F

我不确定我是否正确设置了 gtest 环境。当我用 EXPECT_EQ 做简单的 TEST 时,一切都很好。然而,当我尝试像 TEST_F 这样更高级的东西时,链接器会抱怨。

源代码:

class MyTest : public testing::Test
{
protected:
    static const int my_int = 42;
};

TEST_F(MyTest, test)
{
    EXPECT_EQ(my_int, 42);
}

这给出了

Undefined symbols for architecture x86_64:
  "MyTest::my_int", referenced from:
      MyTest_test_Test::TestBody() in instruction_test.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [tests/tests/run_tests] Error 1
make[2]: *** [tests/tests/CMakeFiles/run_tests.dir/all] Error 2
make[1]: *** [tests/tests/CMakeFiles/run_tests.dir/rule] Error 2
make: *** [run_tests] Error 2

知道为什么会这样吗?

我设法解决了问题,但我不知道为什么会这样:

所以在我使用static const int my_int之前,我必须在MyTest之外再次声明它class:

class MyTest : public testing::Test
{
protected:
    static const int my_int = 42;
};

const int MyTest::my_int;    

TEST_F(MyTest, test)
{
    EXPECT_EQ(my_int, 42);
}

这不是 googletest 的问题,而是 C++ 的语义。

原因: 我们只能在 class 上调用静态 class 成员,而不能在 class 的对象上调用。这是可能的,即使不存在实例。这就是为什么每个静态成员实例都必须初始化,通常在 cpp 文件中。