问题 Gtest:未定义的参考文献


我正在尝试使用GoogleTest来测试一个简单的函数,但是当我运行时 make 在我的构建文件夹中,编译器抛出 Undefined Reference 我的错误信息。我引用了gtest头文件,所以我不确定是什么问题。有任何想法吗?我是unix和单元测试的全部主题的新手,所以我很可能会错过一些简单的东西。提前致谢!

错误消息:

CMakeFiles/Proj2.dir/main.cpp.o: In function `main':
main.cpp:(.text+0x1e): undefined reference to `testing::InitGoogleTest(int*, char**)'
main.cpp:(.text+0x23): undefined reference to `testing::UnitTest::GetInstance()'
main.cpp:(.text+0x2b): undefined reference to `testing::UnitTest::Run()'
collect2: error: ld returned 1 exit status

main.cpp中

#include "gtest/gtest.h"

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

TEST.CPP

#include "gtest/gtest.h"
#include "Testable.h"

TEST(GetTwoTest, Two) {
    EXPECT_EQ(2, GetTwo());
}

Testable.cpp

#include "Testable.h"

int GetTwo() {
    return 3;
}

这是我的CMakeLists.txt文件:

cmake_minimum_required(VERSION 2.6)

SET(CMAKE_CXX_FLAGS "-std=gnu++11") #Turn on C++11 Support

set(FILES_TO_TEST Testable.cpp)
set(UNIT_TESTS Test.cpp)
set(MAIN_FILE main.cpp)

add_subdirectory(gtest) #Build all the gtest stuff
include_directories(gtest/include)
include_directories(.)
add_library(codeToTest ${FILES_TO_TEST})

add_executable(Proj2 ${MAIN_FILE})
target_link_libraries(Proj2 codeToTest)

add_executable(unit-test ${UNIT_TESTS})
target_link_libraries(unit-test gtest gtest_main rt pthread codeToTest)

8122
2017-09-30 00:10


起源

添加了cmake标签 - PiotrNycz
请注意,Google建议您不要构建库,而是将GTest代码包含在项目中。看到 code.google.com/p/googletest/wiki/... - Mawg


答案:


您的设置看起来几乎是正确的。但是,你需要分开2个 main 功能;一个用于真正的可执行文件 Proj2 另一个包含gtest包含和测试可执行文件的函数 unit-test

你可以通过拥有2个不同的main.cpp文件来实现,比如main.cpp和test_main.cpp。你展示的那个将是test_main.cpp,并将被包含在 add_executable(unit-test ... 命令。

你的新main.cpp没有引用gtest,包括或函数。


8
2017-09-30 09:38



谢谢,这是我的问题。我在CMakeLists文件中使用gtest_main,所以我只需要删除main.cpp中的gtest函数。 - Vance


从链接器错误中可以看出,您没有将gtest库链接到测试程序。

看到 底漆

要使用Google Test编写测试程序,您需要将Google Test编译到库中并将测试与其链接。 ...

有关编译器和系统的详细信息,请参阅此文档。


5
2017-09-30 00:54



谢谢您的帮助。我阅读了你提供的链接,但它似乎跳过正确链接gtest库的细节(因为我没有使用IDE)。我使用CMake生成构建文件,这是链接应该发生的地方,不是吗?我提供了我的CMakeLists.txt文件以进一步说明 - Vance
点击此链接: stackoverflow.com/questions/8507723/... - PiotrNycz