[CMake] Absolute Path linking library

Clinton Stimpson clinton at elemtech.com
Wed Sep 4 10:57:54 EDT 2013


On Tuesday, September 03, 2013 09:47:45 PM Laurent Chauvin wrote:
> Hello everyone,
> 
> I'm working on a library, and I would like the users be able to create their
> own program and liking to my library (by specifying path in cmake).
> 
> I created the library and an example to test it.
> Everything compiles.
> 
> However, when I try to run my example I have this error:
> MyExample:
> 	libMyLib.1.dylib (compatibility version 1.0.0, current version 1.0.0)
> 	/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version
> 56.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current
> version 169.3.0)
> 
> The problem is my example is not in the same directory as my library (not
> even in a subdirectory). And it seems it's linking to my library with a
> relative path.
> 
> If I add the path of my library in DYLD_LIBRARY_PATH it works, but I would
> like the users to be able to compile and link straight forward.
> 
> To link the library to my example I use find_package(MyLib REQUIRED) and
> include(${MyLib_USE_FILE}) which basically do a LINK_DIRECTORIES with the
> absolute path of the library.
> 
> Then I do add_executable and target_link_libraries(MyExample
> ${MyLib_LIBRARIES})
> 
> Compilation is working fine. There is these options:
> 
> -L/Absolute/Path/To/MyLib -lMyLib
> 
> But at runtime, library cannot be found.
> 
> Would it be possible to put the full path of my library when linking in the
> CMakeLists ?
> 

You should use the full path to the library instead of LINK_DIRECTORIES.
Its easiest if you use install(EXPORT ...) to have CMake generate an export 
file for you that can be included by your FindMyLib.cmake file.
That export file will use the full path, and include any other necessary 
information about the library.

But to solve the problem of finding the library at runtime (specifying a full 
path won't solve it), CMake 2.8.12 has a new feature to address exactly that 
problem.  For details: http://www.kitware.com/blog/home/post/510

If you can use CMake 2.8.12, then you need to put 
 set(MACOSX_RPATH 1)
in the CMakeLists.txt of MyLib.

If the user is using 2.8.12, then any executable they compile with your 
library will be able to find the library, no matter where it is.

By the way, 2.8.12 is in a release candidate stage right now, and right now 
would be a good time for you to test the new feature that is meant to solve 
your problem.

Clint


More information about the CMake mailing list