Undefined reference to function CMake
Solution 1
Make sure that your test CMakeLists.txt links to the created library.
project(test)
cmake_minimum_required(VERSION 2.8)
set(SOURCE_FILES main.cpp)
include_directories( test2 )
#here
link_directories(test2)
add_subdirectory(test2)
add_executable( ${PROJECT_NAME} ${SOURCE_FILES} )
#and here
target_link_libraries( ${PROJECT_NAME} test2 )
Solution 2
Function add_subdirectory($dir) does not automatically add $dir to include directories and link directories. To use library test2 you should do it manually in CMakeLists.txt of test directory:
include_directories(test2/)
link_directories(test2/)
Then, link your executable with test2 library to get functions definitions. Add to CMakeLists.txt of test directory:
target_link_libraries(tests test2)
Related videos on Youtube
Exagon
Updated on April 21, 2020Comments
-
Exagon about 3 yearsI 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.txtthe 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.cppimplements a function which is defined infoo.hppfor this function I am getting the undefined reference error. What am I doing wrong? How can I get rid of this linker errorEDIT: 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
test2EDIT: solved it it was only a typo in the CMakeLists.txt of test2.
-
Exagon almost 7 yearsIf I am using this I am getting this error:/usr/bin/ld: cannot find -ltest2 -
davepmiller almost 7 yearsAdded a line, give the top level a local for link directories. -
davepmiller almost 7 yearsDo you want it to be *.a or *.so? This implemenation generates a *.a file in the build directory. -
Exagon almost 7 yearsi tried it with link_directories(test2) also with absolute paths but it keep saying "udefined reference to..." -
davepmiller almost 7 years@Exagon. Did you get it working? Sorry, I've been away from computer for a couple days.