[cmake-developers] "Linking" of Object Libraries

Brad King brad.king at kitware.com
Mon May 21 10:54:00 EDT 2018


On 05/20/2018 02:21 PM, Gößwein Matthias / eeas gmbh wrote:
> I found a strange behavior within the object libraries in the upcoming
> CMake 3.12 (I used 3.11.20180519-gdb88f for testing).

Thanks for trying it out!

> If I have for example two object libraries, which are used in one
> executable:
> 
> add_library(ObjLib1 OBJECT ObjLib1.c)
> target_include_directories(ObjLib1 PUBLIC ...)
> 
> add_library(ObjLib2 OBJECT ObjLib2.c)
> target_include_directories(ObjLib2 PUBLIC ...)
> 
> add_executable(MyExe main.c)
> target_link_libraries(MyExe ObjLib1 ObjLib2)
> 
> Then this works fine.

Good.

> But if for some reason one object library "links"
> to the other and this is used for the executable then it does not work:
> 
> add_library(ObjLib1 OBJECT ObjLib1.c)
> target_include_directories(ObjLib1 PUBLIC ...)
> target_link_libraries(ObjLib1 PUBLIC ObjLib2)
> 
> add_library(ObjLib2 OBJECT ObjLib2.c)
> target_include_directories(ObjLib2 PUBLIC ...)
> 
> add_executable(MyExe main.c)
> target_link_libraries(MyExe ObjLib1)
> 
> I only get the usage requirements of ObjLib2, but not the object files
> of ObjLib2 into the executable.

This is expected as things are currently designed.  Object files are
only linked when the object library is *directly* referenced by a
target.  Only usage requirements are transitive, not the object files.

> If I use STATIC Libraries instead it works.
> I read the documentation too and i know that
> there is no link step for object libraries, but I guess it's the same
> for the static libraries

Static libraries have an archiving step rather than a link step and
plays the role of collecting object files together.  Object libraries
have no such step.

A major distinction is that listing object files on a link line causes
them to be included in the link unconditionally.  We can't simply list
all object library transitive dependencies or their objects may be
included multiple times in one target or duplicated in multiple
dependent targets.

> usage of object libraries which depend on other object libraries
> is not working well...I have to repeat in some sort the dependency

Yes, and this is because object libraries are meant to be building
blocks for normal libraries and executables.  How they are packaged
into those libraries and executables needs to be in full control of
project code.  For example, maybe your ObjLib2 objects are supposed
to go into some static library that MyExe links.

-Brad


More information about the cmake-developers mailing list