代码之家  ›  专栏  ›  技术社区  ›  Uduse

G使用测试F时测试未定义的符号

  •  0
  • Uduse  · 技术社区  · 7 年前

    TEST 具有 EXPECT_EQ 东西,都很好。然而,当我尝试更喜欢的东西时,比如 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
    

    知道为什么会这样吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Soeren    7 年前

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

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

        2
  •  1
  •   Uduse    7 年前

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

    static const int my_int ,我必须在MyTest类之外再次声明它:

    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);
    }