簡體   English   中英

gtest –使用TEST_F時未定義的符號

[英]gtest –– Undefined symbols when using TEST_F

我不確定我是否正確設置了我的gtest環境。 當我對EXPECT_EQ進行簡單的TEST時,一切都很好。 但是,當我嘗試像TEST_F這樣的更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 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 ++的語義。

原因:我們只能在類上調用靜態類成員,而不能在類的對象上調用。 即使沒有實例存在,這也是可能的。 因此,通常必須在cpp文件中初始化每個靜態成員實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM