Felix
Felix

Reputation: 121

CMAKE linker does not find library; but library is found with find_library

I have a catkin library under the Name mylib which I build with catkin build Furthermore, I have a node in which uses functions from this library. I enabled this link as I usually do in the CMakeLists.txt of the node:

find_package(catkin REQUIRED COMPONENTS
  mylib
)

add_executable(exec
  src/main.cpp
)

target_link_libraries(exec
  ${catkin_LIBRARIES}
)

However it did not succeed this time. Linker error I then added:

find_package(catkin REQUIRED COMPONENTS
  mylib
)
find_library( MYLIB NAMES
    mylib
)
message(${MYLIB})

add_executable(exec
  src/main.cpp
)

add_dependencies(exec ${MYLIB})

target_link_libraries(exec
  ${catkin_LIBRARIES}
  ${MYLIB}
)

The thing is the message() statement prints the correct path of the library, where i can also find it in the explorer. However I get the warning:

(add_dependencies):   Policy CMP0046 is not set: Error on non-existent dependency in   add_dependencies.

Which refers to the exact same path for the library and says it is not existent.

The linker error is

/usr/bin/ld: cannot find -lmylib

Remark: I could solve the error by adding the path to the library manually

link_directories($ENV{HOME}/test/devel/lib)

I do not understand why the library is found first, but cannot be linked as its package name. But it works by providing the full path. I appreciate any insight!

Upvotes: 1

Views: 1574

Answers (1)

Thomas Sablik
Thomas Sablik

Reputation: 16454

The library is not in your linker path. E.g. your linker looks in /link and you have a lib in /home. You know where to look and can see it in your file browser but the linker won't find it because it only looks in '/link'.

'find_package' looks for the package and sets some variables but it doesn't change the linker path.

You have to set the linker path by yourself. In most cases find_package sets a variable containing the linker path.

find_package provides some functions like catkin_package(). These functions set your build environment.

catkin_package() is a catkin-provided CMake macro. This is required to specify catkin-specific information to the build system which in turn is used to generate pkg-config and CMake files.

This function must be called before declaring any targets with add_library() or add_executable().

Upvotes: 1

Related Questions