[CMake] how to make a static and shared lib at the same time?

Brad King brad.king at kitware.com
Sun Nov 20 11:37:49 EST 2005


Prakash Punnoor wrote:
> I basically want libtool behaviour which creates static and shared libs
> at the same time. This sound like an easy task but I haven't been able
> to achieve this with cmake w/o rebuilding the whole sources for the
> second version lib. :-/

Things like this are harder for CMake because it has to implement them 
on all platforms including Windows.  It also has to get the native tools 
(such as Visual Studio) to build the targets.  This is why not all 
libtool features are implemented in CMake.

> Here is what I tried:
> 
> ADD_LIBRARY(openal-static STATIC ${OPENAL_OBJS})
> SET_TARGET_PROPERTIES(openal-static PROPERTIES OUTPUT_NAME openal)
> SET_TARGET_PROPERTIES(openal-static PROPERTIES LINKER_LANGUAGE C)
> TARGET_LINK_LIBRARIES(openal-static ${ADD_LIBS})
> 
> ADD_LIBRARY(openal SHARED ${OPENAL_OBJS})
> SET_TARGET_PROPERTIES(openal PROPERTIES LINKER_LANGUAGE C)
> SET_TARGET_PROPERTIES(openal PROPERTIES VERSION ${PACKAGE_VERSION}
> SOVERSION ${PACKAGE_MAJOR_VERSION})
> 
> This doesn't work as expected. For building the shared lib, the sources
> get recompiled.

Every target gets its own object file for a given source file.  This is 
necessary to honor target properties like DEFINE_SYMBOL because the 
source must get built with different flags for each target.  Also, when 
building the same source into a static and shared library the shared 
version needs to be compiled with extra flags like -fPIC.  This is why 
the sources get compiled twice.

What you are trying to build is a static archive of shared objects, not 
a static library (though it looks alot like one).  You might be able to 
get things working with careful use of the external object file feature. 
  If you can construct a list of the object files in the shared version 
of the library then you can add them as sources to a static library. 
Look in the CMake/Tests/ExternalOBJ source tree for an example.

This feature will also be useful if it is ever implemented:

http://www.cmake.org/Bug/bug.php?op=show&bugid=1790&pos=1

Having explicit support for this kind of library pair could be useful 
too.  I don't know when we'll get time to implement it but you can at 
least add a feature request:

http://www.cmake.org/Bug

so we don't forget about it.

 > Futhermore The OUTPUT_NAME stuff doesn't seem to work.
> The lib is named openal-static.

Read the documentation of SET_TARGET_PROPERTIES carefully.  The 
OUTPUT_NAME feature currently works only for executables.  Unfortunately 
I don't think you will be able to get two libraries with the same name 
in the same CMake project right now.  The above-mentioned library pair 
feature may be necessary to achieve this.

-Brad


More information about the CMake mailing list