I have a project that uses CMake to get built. I wanted to test my program using GoogleTest.
So I followed the instructions of the ReadMe file of GoogleTest, and added the marked lines to my CMakeLists.txt
(My OS is 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)
My Project structure looks like this:
CrushMapperTest.cpp
looks like the following:
#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);
}
However, if I run the test, I get a lot of undefined reference errors from my linker (here are some of them):
/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()'
Now I am new to using CMake and I don't get what else I need to add to make the linker find the Google Test functions. I was looking through some other SO posts with similar problems ( like this one) a while ago , but so far no suggested solution helped while trying to dowload google test directly through CMake.
What am I doing wrong? Do I need another CMakeLists.txt for the test directory?
Solution
I had to add FetchContent_MakeAvailable(googletest)
after the FetchContent_Declare(...)
line