[CMake] static versus shared libraries with BUILD_SHARED_LIBS

Brad King brad.king at kitware.com
Wed Oct 4 17:44:44 EDT 2006


James Bigler wrote:
> I'm using CMake 2.4.3 on Linux.  When I do:
> 
> OPTION(TEEM_BUILD_SHARED_LIBS "Build Teem with shared libraries." OFF)
> OPTION(BUILD_SHARED_LIBS ${TEEM_BUILD_SHARED_LIBS})
> 
> or
> 
> OPTION(BUILD_SHARED_LIBS "Build package with shared libraries." OFF)

BUILD_SHARED_LIBS does nothing but change the default for ADD_LIBRARY
between SHARED and STATIC.

>     FIND_PACKAGE(PNG)
>     IF(PNG_FOUND)
>       ADD_DEFINITIONS(-DTEEM_PNG=1 ${PNG_DEFINITIONS})
>       SET(TEEM_PNG_LIB ${PNG_LIBRARIES})
>       SET(TEEM_PNG_IPATH ${PNG_INCLUDE_DIR})
>     ENDIF(PNG_FOUND)
> 
> Now I see in my cmake configuration:
> 
>  PNG_LIBRARY                      /usr/lib64/libpng.so
>  PNG_PNG_INCLUDE_DIR              /usr/include
> 
> My packages libraries are built static, but I'm pulling in shared
> versions of external libraries.
> 
> I also have a static version of the library:
> 
> libpng-devel              /usr/lib64/libpng.a
> libpng-devel              /usr/lib64/libpng.so
> 
> Why did FIND_PACKAGE and eventually FIND_LIBRARY expand this to the full
> path and name of the library?

So that CMake knows exactly what library the user wants to use.  If it
just used a library directory and a library name there would be no way
to detect if an extra library in another directory were conflicting.
However there is currently no way to distinguish finding a static and
shared lib:

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

When you build your static release just set the PNG_LIBRARY you want in
your CMakeCache.txt file (through the ccmake dialog for example).

> When I look at the build output I see a spurious -rdynamic instead of
> -static.
> 
> Linking C executable ../../bin/unu
> cd /home/sci/bigler/pub/src/teem/octagon/src/bin && /usr/local/bin/cmake
> -P CMakeFiles/unu.dir/cmake_clean_target.cmake
> cd /home/sci/bigler/pub/src/teem/octagon/src/bin && /usr/bin/gcc    -O3
> -DNDEBUG  -fPIC "CMakeFiles/unu.dir/unu.o"   -o ../../bin/unu -rdynamic
> -L/home/sci/bigler/pub/src/teem/octagon/bin -L/usr/lib64 -lteem -lbz2
> -lz -lpng -lz -lm
> -Wl,-rpath,/home/sci/bigler/pub/src/teem/octagon/bin:/usr/lib64
> 
> I've verified that if I pass -static instead of -rdynamic it does what I
> think it should.

...but it won't with this bug fix:

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

BUILD_SHARED_LIBS does not affect the default type of executables that
are created.  If you want to create a static executable you need to set
CMAKE_EXE_LINKER_FLAGS to -static.  The extra -rdynamic does not hurt
linking statically AFAIK.  It is always added in case one of the
libraries linked is shared.

-Brad


More information about the CMake mailing list