[CMake] Shared library from sources in several subdirectories

Nils Gladitz nilsgladitz at gmail.com
Mon Dec 7 04:08:40 EST 2015



On 12/04/2015 03:05 PM, Bruce Stephens wrote:
> Any suggestions on how to organise that? Presumably there are
> lots of examples in (for example) KDE, but I'm not familiar enough
> with that codebase to be able to find them easily.
>
> Currently our GNU Make build builds static libraries in the 
> subdirectories,
> then those are put into a big static library and that's linked into a 
> shared
> library. (The last step uses a shell script which knows how to do that for
> various platforms.)
>
> My first attempt uses add_library(... OBJECT ...) in the subdirectories,
> then add_library(... SHARED $<TARGET_OBJECTS:...> $<TARGET_OBJECTS:...>)
> to combine them.
>
> That works, though it means repeating the same information (more or 
> less) twice
> since for each add_subdirectory() there'll be a $<TARGET_OBJECTS:>. Also
> the dependent libraries need to be added in the top-level but they're 
> triggered
> by the subdirectory (by the looks of it I can't use 
> target_link_libraries() on an OBJECT
> library). It works, though, and didn't take me very long to do, and 
> the result looks
> clean and relatively easy to follow.
>
> Any better ways to do this? (In the particular case I'm looking at, 
> splitting the
> libraries and just having one per subdirectory might make sense, but 
> not in all
> cases.)

I would avoid creating these single use, per directory libraries entirely.

A single target can build sources located in any number of directories.

If you want to subdivide the source file listing of that one target for 
organizational purposes you can do so with e.g. include(), 
target_sources() and/or list variables.

Nils



More information about the CMake mailing list