[Cmake] Building shared libraries.

Brad King brad.king at kitware.com
Mon Jul 2 15:58:34 EDT 2001


Hello, all:

I have just checked in changes to CMake that Bill Hoffman, Ken Martin, and
I have been discussing for about a week.  We have added support for
selecting static or shared builds on a per-library basis.

The cmTarget type of "LIBRARY" has been split into "STATIC_LIBRARY" and
"SHARED_LIBRARY".  Which is used is selected by the ADD_LIBRARY command as
follows:

ADD_LIBRARY(name_of_lib [STATIC | SHARED] src1 src2 ...)

If the second argument to the ADD_LIBRARY command is exactly "STATIC" or
"SHARED" (after expanding variables), then it is assumed that it specifies
the type of the library.  If not, the second argument is treated as
another source or source list.  In this case, the library type is selected
by the current value of BUILD_SHARED_LIBS, which was the behavior for all
libraries before I made these changes.  Finally, if BUILD_SHARED_LIBS is
not set at all, then the library type defaults to STATIC.

I have tested the changes on the build of Cable, a tool that uses a
mixture of shared and static libraries.  CMake also seems to bootstrap
without a problem.  The tests have been run in both unix and windows
environments.  Let me know if you find any problems.

------------------------------------------------------------------
This approach allows CMakeLists files to create arbitrary groups of
libraries that can be built as shared or static.  For example, one could
write:

OPTION(BUILD_FOO_SHARED "Build the Foo libraries shared." OFF)
OPTION(BUILD_BAR_SHARED "Build the Bar libraries shared." ON)

IF(BUILD_FOO_SHARED)
  SET(FOO_LIBRARY_TYPE SHARED)
ELSE(BUILD_FOO_SHARED)
  SET(FOO_LIBRARY_TYPE STATIC)
ENDIF(BUILD_FOO_SHARED)

IF(BUILD_BAR_SHARED)
  SET(BAR_LIBRARY_TYPE SHARED)
ELSE(BUILD_BAR_SHARED)
  SET(BAR_LIBRARY_TYPE STATIC)
ENDIF(BUILD_BAR_SHARED)

# .....And then later in the file or in any subdirectory:

ADD_LIBRARY(FooLibZero ${FOO_LIBRARY_TYPE} fooZero)
ADD_LIBRARY(FooLibOne ${FOO_LIBRARY_TYPE} fooOne)
ADD_LIBRARY(BarLibZero ${BAR_LIBRARY_TYPE} barZero)
ADD_LIBRARY(BarLibOne ${BAR_LIBRARY_TYPE} barOne)

------------------------------------------------------------------

A corresponding change to these that has not yet been checked in removes
the automatic creation of the BUILD_SHARED_LIBS cache entry that I added
about a week or two ago in place of the "BUILD_SHARED_LIBRARIES" command.  
Since not all libraries can be built shared, we realized that it is a bad
idea to have that variable always sitting around.  Instead of putting the
BUILD_SHARED_LIBRARIES command back, however, the same functionality can
be obtained by using the line:

OPTION (BUILD_SHARED_LIBS "Build shared libraries." OFF)

I plan to check in this change after a few days to give everyone a chance
to change their CMakeLists files.  Again, let me know if you have any
problems.

-Brad





More information about the CMake mailing list