[CMake] build a shared library from static libraries

Alexander Neundorf a.neundorf-work at gmx.net
Tue Mar 4 12:23:14 EST 2008


On Tuesday 04 March 2008, packadal wrote:
> I did used add_subdirectory, and i'm confused about why this does not work
>
> :(
>
> My cmakelists.txt looks like this :
> root dir :
> project(myproject)
> ADD_SUBDIRECTORY(lib1)
> ADD_SUBDIRECTORY(lib2)
>
> TARGET_LINK_LIBRARIES( lib1 lib2)
>
> lib1 dir:
> project(myproject)
>
> set (SOURCES
> sourcefile1.cpp
> sourcefile2.cpp
> sourcefile3.cpp
> )
> add_library(lib1 STATIC SOURCES)

Ok, this line is wrong:
TARGET_LINK_LIBRARIES( lib1 lib2)

What do you want to do ?
If you want to link lib1 against lib2, you have to put this into 
lib1/CMakeLists.txt (but it won't work because lib2 doesn't exist yet at this 
point).

If you want to create a shared library from both lib1 and lib2 you would have 
to do something like the following:

add_subdirectory(lib1)
add_subdirectory(lib2)

add_library(lib3 SHARED file.c)
target_link_libraries(lib3 lib1 lib2)

This will link lib3 against lib1 and lib2. 
If lib1 and/or lib2 are static libs, you will have problems.
Combining static libs into a shared lib is not really portable, you have to 
take care that you use the correct linker flags for the libs so that it will 
work.
I suggest you just build lib3 from all the sorce files:

set(lib1Sources lib1/foo1.c lib1/foo2.c)
set(lib2Sources lib2/bar1.c lib2/bar2.c)

add_library(lib3 SHARED blub.c ${lib1Sources} ${lib2Sources})

This will work everywhere without additional problems.

Alex


More information about the CMake mailing list