[CMake] Extending a target??

Michael Hertling mhertling at online.de
Wed Jun 2 19:53:05 EDT 2010


On 06/02/2010 07:57 PM, Doug Reiland wrote:
> It all goes back to how a current Makefile for a library is setup.
> I need a shared and static version of library.
> 
> The library includes some objects built my sub-directories. In those
> sub-directories, there are unique compile flags, generated files, ...
> 
> In the past, those sub-directories would generate a .o and both the
> shared and static library include it (link, archive).
> 
> This all still works ok in cmake for shared library because you can
> just get the sub-directory to generate a share libray and have main
> library link it in.
> 
> For static library, ... it is a pain.

Typically, object files are compiled with different flags for their
incorporation in static or in shared libraries, e.g. on *nix, they
differ at least in the PIC flag. Thus, each source file should be
compiled twice which is achieved with two ADD_LIBRARY() commands:

ADD_LIBRARY(mylib-static STATIC foo1.c foo2.c foo3.c)
ADD_LIBRARY(mylib-shared SHARED foo1.c foo2.c foo3.c)

For a proper naming of the results, see the target property OUTPUT_NAME.

If you have subdirectories with source files needing to be compiled with
special flags I would recommend to collect these files in a list, impose
appropriate source file properties on them and add them to the sources
of the library/libraries:

SET(MYLIB_SUBDIR_SRCS subdir/bar1.c subdir/bar2.c subdir/bar3.c)
SET_SOURCE_FILES_PROPERTIES(${MYLIB_SUBDIR_SRCS}
PROPERTIRES COMPILE_FLAGS ...)
ADD_LIBRARY(mylib-static STATIC ... ${MYLIB_SUBDIR_SRCS})
ADD_LIBRARY(mylib-shared SHARED ... ${MYLIB_SUBDIR_SRCS})

Regarding generated files, one must differentiate between two cases:

- If you know a priori which files are generated you can usually use
  ADD_CUSTOM_COMMAND(OUTPUT ...) for their generation at build time
  and include them in a target's source file list.
- If you don't know the files or their names a priori, i.e. you can't
  itemize them in a CMakeLists.txt, you could possibly resort on an
  EXECUTE_COMMAND() to generate them at configuration time, catch
  their names and add them to a target's source files, but this
  approach has implications w.r.t. dependency tracking, see
  <http://www.mail-archive.com/cmake@cmake.org/msg29180.html>.

In summary, my advice is to set up the library's source file list
thoroughly and throughout any subdirectories, impose source file
properties as needed and use ADD_CUSTOM_COMMAND(OUTPUT ...) for
generated source files whenever possible. Finally, you should end
up with the two ADD_LIBRARY() commands mentioned above, so building
the two variants of your library could turn out to be quite painless.

'hope that helps.

Regards,

Michael


More information about the CMake mailing list