0

I have a static library in /PATH directory, and when I tried to use the library with link_directories as follows:

link_directories(/PATH)
target_link_libraries(CppHello libHelloLib.a)

I had an error message:

ld: library not found for -lHelloLib
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [/PATH] Error 1
make[2]: *** [CMakeFiles/CppHello.dir/all] Error 2
make[1]: *** [CMakeFiles/CppHello.dir/rule] Error 2

Instead, I had to specify the path as follows to make it work:

target_link_libraries(CppHello /PATH/libHelloLib.a)

What might be wrong? Is this an issue with Cmake on Mac OS X, or did I just miss something?

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
prosseek
  • 182,215
  • 215
  • 566
  • 871
  • 1
    Another problem that you call `link_directories()` **after** creating executable: `link_directories` affects only on targets, created after it: http://stackoverflow.com/questions/33559356/when-i-use-cmake-to-compile-the-file-it-shows-usr-bin-ld-cannot-find-ltest/33562025#33562025 – Tsyvarev Nov 30 '15 at 09:10
  • @Tsyvarev That looks to me like the real answer. The issue of having the prefix and suffix in there doesn't seem to be causing any problem here and my test with CMake shows that it knows to remove them. – bames53 Nov 30 '15 at 09:19
  • @bames53: Yes, the order of the commands definitely affects on correctness. The thing is that I have noticed that misorder only after posting an answer. Then the question is just a duplicate, I see no needs to provide an answer for it in that case. – Tsyvarev Nov 30 '15 at 09:31

1 Answers1

4

You call link_directories() after creating executable: link_directories affects only on targets, created after it: https://cmake.org/cmake/help/v3.4/command/link_directories.html. The result is that the correct -lHelloLib flag is added to the target, but the lib search path isn't updated with a -L/PATH flag.

Instead put the call to link_directories() before you create any targets.


Since 3.3 version CMake documentation for target_link_libraries explicitely specifies, which kind of items for link it accepts. Among them:

  • A full path to a library file
  • A plain library name

So, you should specify either full path to the library file, or only name for the library, without file's extension(.a) and prefix(lib). Error message in you case shows, that CMake has tried to handle even filename-only library, but without success(some sort of Undefined Behaviour).

While previous versions of CMake doesn't document this command so clear, they, probably, follow same convention.

bames53
  • 86,085
  • 15
  • 179
  • 244
Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
  • "You call link_directories() **AFTER** creating executable: link_directories affects only on targets, created **AFTER** it" -- I read the documentation multiple times, and yet I somehow didn't grasp that one crucial sentence... – bcause Jun 17 '16 at 01:38