首页 > 解决方案 > 将 GoogleTest 添加到现有项目会导致链接器错误

问题描述

我有一个使用 CMake 构建的项目。我想使用 GoogleTest 测试我的程序。所以我按照 GoogleTest 的自述文件的说明,将标记的行添加到我的CMakeLists.txt(我的操作系统是 Ubuntu 20.04.3 LTS):

cmake_minimum_required(VERSION 3.20)
project(replicatorProject)

set(CMAKE_CXX_STANDARD 14)

### I added the the following lines which I got from the ReadMe of GoogleTest 

include(FetchContent)
FetchContent_Declare(
        googletest
        # Specify the commit you depend on and update it regularly.
        URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
)

# Now simply link against gtest or gtest_main as needed. Eg
add_executable(example test/CrushMapperTest.cpp)
target_link_libraries(example gtest_main)
add_test(NAME example_test COMMAND example)

### until here (above)

find_library(CRUSH_LIBRARY libcrush.so /usr/local/lib/crush/ REQUIRED)
find_package(CppKafka REQUIRED)
add_executable(replicator src/main.cpp src/kafka/KafkaConsumer.cpp src/kafka/KafkaConsumer.h src/crush/CrushMapper.cpp src/crush/CrushMapper.h src/Replicator.cpp src/Replicator.h src/crush/Bucket.cpp src/crush/Bucket.h src/crush/Device.cpp src/crush/Device.h)
target_link_libraries(replicator LINK_PUBLIC ${CRUSH_LIBRARY} CppKafka::cppkafka)
target_include_directories(replicator PRIVATE /usr/local/include)

我的项目结构如下所示:

项目结构

CrushMapperTest.cpp如下所示:

#include "gtest/gtest.h"

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

TEST(case1, name){
    EXPECT_EQ(1,1);
}

但是,如果我运行测试,我会从链接器中得到很多未定义的引用错误(这里有一些):

/usr/bin/ld: /home/lorik/Uni/Praktikum/Projekt/replicator/test/CrushMapperTest.cpp:13: undefined reference to `testing::internal::AssertHelper::~AssertHelper()'
/usr/bin/ld: /home/lorik/Uni/Praktikum/Projekt/replicator/test/CrushMapperTest.cpp:13: undefined reference to `testing::internal::AssertHelper::~AssertHelper()'

现在我是使用 CMake 的新手,我没有得到我需要添加的其他内容以使链接器找到 Google 测试功能。不久前,我正在查看其他一些有类似问题的 SO 帖子(比如这个),但到目前为止,在尝试通过 CMake 直接下载谷歌测试时,没有建议的解决方案有帮助。

我究竟做错了什么?我需要另一个 CMakeLists.txt 作为测试目录吗?

解决方案

我必须在行FetchContent_MakeAvailable(googletest)后添加FetchContent_Declare(...)

标签: c++cmakegoogletest

解决方案


推荐阅读