ruipacheco
ruipacheco

Reputation: 16442

How to link to static library?

I have an executable that links to a static library I build and another library that is provided to me already built.

I'm trying to get cmake to link to it but I always get the following error:

ld: library not found for -lsrc/thislibrary/libthislibrary.a
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[2]: *** [MyExecutable] Error 1
make[1]: *** [CMakeFiles/DocumentParserTests.dir/all] Error 2
make: *** [all] Error 2

These are my build instructions:

add_executable(MyExecutable tests/MyExecutable.cpp)
target_link_libraries(MyExecutable statictests)
target_link_libraries(MyExecutable myownlib)
target_link_libraries(MyExecutable src/thislibrary/libthislibrary.a)

Both statictests and myownlib build flawlessly.

Upvotes: 0

Views: 178

Answers (1)

Peter
Peter

Reputation: 14947

CMake is running the link command from a different working directory than you expect. Instead of using bare relative paths in a CMakeLists.txt file, use the special variables ${CMAKE_SOURCE_DIR}, ${CMAKE_CURRENT_SOURCE_DIR}, ${CMAKE_BINARY_DIR}, etc.

For a quick cheat-sheet of the meanings of these, see http://www.cmake.org/Wiki/CMake_Useful_Variables, or see the CMake documentation.

In your case, I suspect the correct path location is this:

target_link_libraries(MyExecutable ${CMAKE_CURRENT_SOURCE_DIR}/src/thislibrary/libthislibrary.a)

Upvotes: 2

Related Questions