[CMake] Delivering imported libraries with binaries on Linux

Michael Hertling mhertling at online.de
Fri Oct 14 11:12:16 EDT 2011


On 10/12/2011 07:38 PM, Harelick, Matthew wrote:
> Hello:
> 
> 
> I am working on a project that relies on third party libraries, for example MyVendor.so.   I am using cmake 2.6.  [...]

Uh-oh... No chance to upgrade?

> [...] When the third party shared object is checked out, it is installed in svnroot/Thirdparty/MyVendor/lib/MyVendor.so
> 
> I add the library has an imported library.  When I build the application, the location of the library is linked to the precise location above.
> 
> How do I:
> 
> 1)      Encode cmake to generate a make file that copies the library into a location relative to the binary, like
> ../lib so that I can then use that directory as an import location.  I can copy the file myself manually but it would nice if I could use cmake to help with doing this automatically.  I know that if I was handwriting a makefile I could in effect build a library target by copying one from a different location.

You might use a custom command for this purpose, look here:

CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR)
PROJECT(THIRDPARTY C)
SET(CMAKE_VERBOSE_MAKEFILE ON)
FILE(WRITE ${CMAKE_BINARY_DIR}/f.c "void f(void){}\n")
EXECUTE_PROCESS(COMMAND gcc -fPIC -c f.c)
EXECUTE_PROCESS(COMMAND gcc -shared -o libf.so f.o)
ADD_CUSTOM_COMMAND(OUTPUT ${CMAKE_BINARY_DIR}/lib/libf.so
    COMMAND ${CMAKE_COMMAND} -E copy_if_different
        ${CMAKE_BINARY_DIR}/libf.so ${CMAKE_BINARY_DIR}/lib/libf.so
    DEPENDS ${CMAKE_BINARY_DIR}/libf.so)
ADD_LIBRARY(f SHARED IMPORTED)
SET_TARGET_PROPERTIES(f PROPERTIES IMPORTED_LOCATION "./lib/libf.so")
FILE(WRITE ${CMAKE_BINARY_DIR}/main.c
"int main(void){f(); return 0;}\n")
ADD_EXECUTABLE(main main.c ${CMAKE_BINARY_DIR}/lib/libf.so)
TARGET_LINK_LIBRARIES(main f)

The custom command copies the "third-party" library libf.so from
CMAKE_BINARY_DIR to CMAKE_BINARY_DIR/lib, and the main target refers
to that library by an IMPORTED_LOCATION property with a relative path
as desired. Note that the custom command's OUTPUT must be referred to
by a target; if necessary, use a custom one instead of ADD_EXECUTABLE().

> 
> 2)      How do I ensure that CPack maintains that relative structure so that internally the application looks in ../lib for the file to dynamically load?

Does CPack fail in this regard? I'm not quite sure what you mean;
what happens now, and what do you want to happen instead?

Regards,

Michael


More information about the CMake mailing list