I'm trying to add unit tests to my c++ project using googletest. I have the following folder structure:
*--build
|---(building cmake here)
|
*--main.cpp
|
*--CMakeLists.txt (root)
|
*--modules
|---foo
*------foo.h
|------foo.cpp
|------CMakeLists.txt
*------test
|--------main.cpp
|--------CMakeLists.txt
And the code below for the CMakeLists.txt files:
CMakeLists.txt (root)
cmake_minimum_required(VERSION 3.15.2)
project(foobar)
add_executable(${PROJECT_NAME} main.cpp)
add_library(foolib STATIC)
# Build sub-modules
include_directories(modules/foo)
add_subdirectory(modules/foo)
target_link_libraries(${PROJECT_NAME} PRIVATE foolib)
target_link_libraries(foo_test PRIVATE gtest_main foolib)
CMakeLists (foo module)
file(GLOB FOO_SRC *.h *.cpp)
target_include_directories(foolib PUBLIC
${CMAKE_CURRENT_SOURCE_DIR})
# add sources to the library
target_sources(foolib PUBLIC ${FOO_SRC})
# bootstrap gtest
if(BUILD_TESTS)
enable_testing()
add_subdirectory(test)
endif()
CMakeLists (test)
file(GLOB TEST_SRCS *.h *.cpp)
target_include_directories(foolib PUBLIC
${CMAKE_CURRENT_SOURCE_DIR})
# add sources to the library
target_sources(foolib PUBLIC ${FOO_SRC})
include_directories(googletest)
include_directories(
${CMAKE_SOURCE_DIR}/modules/foo
)
add_executable(foo_test ${TEST_SRCS})
gtest_discover_tests(foo_test)
And finally the test main.cpp
#include <iostream>
#include <string>
#include "../foo.h"
TEST(builder_tests, initial_test)
{
std::string s = "please work";
Foobar fb(s);
EXPECT_EQ(fb.test_string, "please work");
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
However, I get the equiveant of the following error when I try to make the test project:
Linking CXX executable FOO_TEST
/usr/bin/ld: CMakeFiles/FOO_TEST.dir/main.cpp.o: in function `foo_tests_initial_test_Test::TestBody()':
/inference/modules/foo/test/main.cpp:15: undefined reference to `foo::foo(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: error: ld returned 1 exit status
make[3]: *** [modules/foo/test/CMakeFiles/foo_TEST.dir/build.make:234: modules/foo/test/FOO_TEST] Error 1
make[2]: *** [CMakeFiles/Makefile2:842: modules/foo/test/CMakeFiles/FOO_TEST.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:849: modules/foo/test/CMakeFiles/FOO_TEST.dir/rule] Error 2
make: *** [Makefile:383: FOO_TEST] Error 2
My main project builds fine and runs, so I don't understand why the test project doesn't even though it's linking the same library in the same fashion.
Also it feels like I'm not using the correct structure to build my unit tests here, so any additional feedback there would be much appreciated.
Thank you!