[CMake] embedding lib into a shared object

Michael Hertling mhertling at online.de
Wed Sep 29 21:22:00 EDT 2010


On 09/29/2010 12:26 PM, Ovanes Markarian wrote:
> Hello *,
> 
> I have some library available as a Linux lib file. Now I need to create a
> shared object (actually a MODULE in terms of CMake) out of this lib. The
> module is later on loaded using the dlopen-API function.
> 
> I created a sample project with
> 
> /
> +-- testlib
> +-- so
> 
> 
> testlib - consists of a single cpp file haveing a global variable and a
> function returning it.
> 
> CMake script:
> CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
> 
> PROJECT(testlib CXX)
> 
> add_library(testlib STATIC functions.cpp)
> 
> 
> so - consists of a cpp file and links against testlib.
> 
> CMake script:
> CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
> 
> PROJECT(so CXX)
> 
> add_library(so MODULE main.cpp)
> target_link_libraries(so testlib)
> set_target_properties (so PROPERTIES VERSION 1.0 LINKER_LANGUAGE CXX)
> 
> and the Root CMakeLists.txt which should build both:
> 
> CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
> 
> PROJECT(dll_test CXX)
> 
> add_subdirectory(lib)
> add_subdirectory(so)
> add_dependencies(so lib)
> 
> 
> Now my problem is that after the build I can find the symbols from
> functions.cpp in the lib file using the nm tool. But these symbols are not
> part of the so. How can I force them to be part of the so-Module?

man ld:

[...]
--whole-archive
    For each archive mentioned on the command line after the --whole-
    archive option, include every object file in the archive in the
    link, rather than searching the archive for the required object
    files. This is normally used to turn an archive file into a
    shared library, forcing every object to be included in the
    resulting shared library. This option may be used more than once.

    Two notes when using this option from gcc: First, gcc doesn’t know
    about this option, so you have to use -Wl,-whole-archive. Second,
    don’t forget to use -Wl,-no-whole-archive after your list of
    archives, because gcc will add its own list of archives to your
    link and you may not want this flag to affect those as well.
[...]

E.g., you can use the LINK_FLAGS target property to enable this option,
and don't forget -fPIC and 'extern "C"' for functions.cpp's dlopening.

Besides, the ADD_DEPENDENCIES() is not necessary because of the
TARGET_LINK_LIBRARIES(), and wouldn't it be worth considering to
compile the dl-suitable module from the static library's sources?

Regards,

Michael


More information about the CMake mailing list