I am trying to learn CMake, but I get a undefined reference to ... linker error I have a directory with a subdirectory. each of them has its own CMakeLists.txt
test
|----main.cpp
|----CMakeLists.txt
|----test2
|----foo.hpp
|----foo.cpp
|----CMakeLists.txt
the CMakeLists.txt for test is:
cmake_minimum_required(VERSION 3.5)
project(tests)
add_subdirectory(test2)
set(SOURCE_FILES main.cpp)
add_executable(tests ${SOURCE_FILES})
the CMakeLists.txt for test2 is:
set(test2_files
foo.cpp
foo.hpp
)
add_library(test2 ${test2_files})
foo.cpp
implements a function which is defined in foo.hpp
for this function I am getting the undefined reference error.
What am I doing wrong? How can I get rid of this linker error
EDIT: My CMakeLists.txt now looks like this, but I still get the linker error:
project(tests)
cmake_minimum_required(VERSION 2.8)
set(SOURCE_FILES main.cpp)
include_directories(test2)
link_directories(test2)
add_subdirectory(test)
add_executable( ${PROJECT_NAME} ${SOURCE_FILES} )
target_link_libraries(${PROJECT_NAME} test2)
I also tried it with the absolute path instead of test2
EDIT: solved it it was only a typo in the CMakeLists.txt of test2.
Make sure that your test
CMakeLists.txt
links to the created library.Function
add_subdirectory($dir)
does not automatically add$dir
to include directories and link directories. To use librarytest2
you should do it manually in CMakeLists.txt oftest
directory:Then, link your executable with
test2
library to get functions definitions. Add to CMakeLists.txt oftest
directory: