8

I have a CMakeLists.txt file, with the following:

target_link_libraries(${PROJECT_NAME} OpenNI2)

When I run cmake, I receive no errors. But when I run make, I receive the following error:

/usr/bin/ld: cannot find -lOpenNI2

However, I have a file called libOpenNI2.so in my build directory. So why can ld not find this? I thought that the build directory was on the search path for target_link_libraries?

Thanks!

Karnivaurus
  • 22,823
  • 57
  • 147
  • 247

2 Answers2

4

That's because when linking, the linker doesn't look in the current directory but only in a set of predefined directories.

You need to tell CMake where the library is, for example by giving the full path to the library in the target_link_library command, or adding it as an imported library.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

it works if adding like:

target_link_libraries(${PROJECT_NAME} /path_to_library_build/libOpenNI2.a)

details:

ld is looking for the libraries in a very short list of folders defined in

/etc/ld.so.conf

and it usually looks like following:

include /etc/ld.so.conf.d/*.conf

and actual paths list from those *.conf files usually is like:

# Legacy biarch compatibility support
/lib32
/usr/lib32
# Multiarch support
/usr/local/lib/x86_64-linux-gnu
/lib/x86_64-linux-gnu
/usr/lib/x86_64-linux-gnu

if your project linking library is not in the folder of this list, ld won't find it unless either a special linking variable set LD_LIBRARY_PATH with the path to your library or a complete path/library name provided in cmake target_link_libraries directive.

details on how to proper setup LD_LIBRARY_PATH variable discussed here

Oleg Kokorin
  • 2,288
  • 2
  • 16
  • 28
  • 1
    Hey, thanks for the answer! Could you give a bit of explanation? It would help OP and future readers :) – xShirase Oct 17 '20 at 23:47
  • @Oleg Kokorin Both static and shared versions of a specific library are in the same folder, then which library does Cmake prefer to link to when invoking target_link_libraries(target_name, library_name_without_postfix)? – John Jun 13 '21 at 14:35