【问题标题】:Gtest: Undefined ReferencesGtest:未定义的引用
【发布时间】:2012-09-21 09:02:27
【问题描述】:

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

错误信息:

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

可测试的.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)

【问题讨论】:

标签: c++ unit-testing unix cmake googletest


【解决方案1】:

您的设置看起来几乎正确。但是,您需要有 2 个独立的 main 函数;一个用于真正的可执行文件Proj2,另一个用于测试可执行文件unit-test

您可以通过拥有 2 个不同的 main.cpp 文件来做到这一点,例如 main.cpp 和 test_main.cpp。您显示的将是 test_main.cpp,并将包含在 add_executable(unit-test ... 命令中。

您的新 main.cpp 将不会引用 gtest,无论是包含还是函数。

【讨论】:

  • 谢谢,这是我的问题。我在 CMakeLists 文件中使用 gtest_main,所以我只需要删除 main.cpp 中的 gtest 函数。
【解决方案2】:

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

Primer:

要使用 Google Test 编写测试程序,您需要将 Google Test 编译成一个库并将您的测试与它链接起来。 ...

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

【讨论】:

  • 感谢您的帮助。我阅读了您提供的链接,但它似乎跳过了正确链接 gtest 库的详细信息(因为我没有使用 IDE)。我使用 CMake 生成构建文件,所以这就是链接应该发生的地方,不是吗?我提供了我的 CMakeLists.txt 文件以供进一步说明
【解决方案3】:

libgtest.a 放在您的目标文件之后

如果您是手动操作而不是使用 CMake,请确保这样做:

g++ main.cpp googletest/build/lib/libgtest.a

代替:

g++ googletest/build/lib/libgtest.a main.cpp

这是我测试过的完整工作示例:https://askubuntu.com/questions/97626/how-to-install-googletest/1295185#1295185

这个问题不是 GoogleTest 独有的:我也可以用 minimal library example like this oneEli explainss 重现它,我现在没有耐心学习的排序规则。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-08
    • 2014-09-09
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 2020-08-19
    • 2017-06-28
    相关资源
    最近更新 更多