You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

现有CMake项目接入GoogleTest出现链接器错误如何解决

问题描述
  • 运行环境:Ubuntu 20.04.3 LTS,CMake 3.20+ 构建C++项目
  • 需求:集成GoogleTest实现单元测试

原项目根目录CMakeLists.txt配置如下:

cmake_minimum_required(VERSION 3.20)
project(replicatorProject)

set(CMAKE_CXX_STANDARD 14)

### 从GoogleTest官方README添加的代码
include(FetchContent)
FetchContent_Declare(
        googletest
        # 指定依赖的提交版本并定期更新
        URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
)

# 原配置直接声明测试用例和链接
add_executable(example test/CrushMapperTest.cpp)
target_link_libraries(example gtest_main)
add_test(NAME example_test COMMAND example)
### 以上为添加的GTest相关代码

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

错误现象:构建测试程序时链接器报大量GoogleTest相关符号未定义引用,报错示例:

/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()'

解决方案

问题出在仅使用FetchContent_Declare声明了googletest依赖,没有触发依赖的拉取、构建和目标导入流程,导致CMake识别不到gtest_main链接目标,无法正确关联GTest库。

只需在FetchContent_Declare(...)代码块后添加一行配置即可:

FetchContent_MakeAvailable(googletest)

FetchContent_MakeAvailable是CMake 3.14及以上版本提供的接口,会自动完成依赖的下载、编译、安装,并将依赖导出的目标(如gtest、gtest_main)暴露到当前项目的作用域中,后续链接时就能正确找到GTest的符号定义,无需单独为test目录编写CMakeLists.txt。


内容的提问来源于stack exchange,提问作者L.Gashi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 06:36:03