Undefined reference to function CMake

47,678

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)
Share:
47,678

Related videos on Youtube

Exagon
Author by

Exagon

Updated on April 21, 2020

Comments

  • Exagon
    Exagon about 3 years

    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.

  • Exagon
    Exagon almost 7 years
    If I am using this I am getting this error: /usr/bin/ld: cannot find -ltest2
  • davepmiller
    davepmiller almost 7 years
    Added a line, give the top level a local for link directories.
  • davepmiller
    davepmiller almost 7 years
    Do you want it to be *.a or *.so? This implemenation generates a *.a file in the build directory.
  • Exagon
    Exagon almost 7 years
    i tried it with link_directories(test2) also with absolute paths but it keep saying "udefined reference to..."
  • davepmiller
    davepmiller almost 7 years
    @Exagon. Did you get it working? Sorry, I've been away from computer for a couple days.

Related