Gtest:未定义的参考

我试图使用GoogleTest来testing一个简单的函数,但是当我运行在我的生成文件夹中,编译器会抛出Undefined Reference错误消息在我身上。 我已经引用了gtest头文件,所以我不知道什么是错的。 有任何想法吗? 我对unixunit 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()); } 

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) 

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

你可以做两个不同的main.cpp文件,比如main.cpp和test_main.cpp。 你所显示的是test_main.cpp,并且会包含在add_executable(unit-test ...命令)中。

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

从链接器错误很明显,你没有链接gtest库到你的测试程序。

请参阅http://code.google.com/p/googletest/wiki/Primer

要使用Google Test编写测试程序,您需要将Google Test编译到一个库中,并将其与您的测试链接起来。 …

只要看到这个文档有关您的编译器和系统的详细信息。