c++ - 将 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(...)
解决方案
推荐阅读
- arrays - 试图在 kotlin 数组中找到最小的数字
- r - n_distinct(x) 和 length(unique(x)) 在闪亮时不起作用
- javascript - JS 将模板文字转换回字符串连接?
- python - pyppeteer.errors.TimeoutError: Navigation Timeout Exceeded: 超过 8000 ms
- angular - 使用 Jest 和 Spectator 测试 Angular 拦截器响应
- r - R中的潜在特征模型
- c - 链接器无法区分函数和变量?
- python - Python 递归辅助方法返回 none 而不是 int
- r - 删除 R 中的重复行
- angular - 如何解决 Angular 10 部署到 Heroku 时出现错误 503 的问题