Is it an indented feature or a bug that OBJECT libraries does not propagate transient dependencies?

If I have a project with 3 different modules that depend on each other like this:

mycorelib ← mylib ← myapp

myapp is an executable. If I build mycorelib and mylib as STATIC libraries then everything works out fine. mylib has dependency on mycorelib so mycorelib will be included as part of the link step when building myapp.

However if I build mycorelib and mylib as OBJECT libraries then the dependency chain breaks and mycorelib is not included in the link step of myapp and I get undefined symbol errors. I made this test repository to illustrate the feature:
https://bitbucket.org/andersrein/cmake-object-library-test/

On the master branch I build mycorelib and mylib as OBJECT libraries and the build fails. On the staticlib branch I build with static libraries and the build works (at least on linux).

Is this the way OBJECT libraries are intented to work or is this a bug?

You can’t link directly against an object library. An object library just produces .o files that are to be used as the input for another static or shared library

I dont’ think that is correct. See https://cmake.org/cmake/help/latest/command/add_library.html#object-libraries:

New in version 3.12: Object libraries can be linked to with target_link_libraries().

Besides, I’m only encountering problems with OBJECT libraries once I have two level of dependencies. If it is only mylib ← myapp then it works fine to build mylib as a OBJECT library.

Linking of object libraries is a bit special (and part of the reason I suggest only using them if you really have to - most of the time you really do want a static library instead). Only targets that link directly to an object library will have that object library’s objects included in its linker command. If you are only linking indirectly to it through another target, you still get the object library’s usage requirements, but not its objects.

The background for this behavior relates to avoiding adding the same object files multiple times, which would generally result in an error due to duplicate symbols. If you want the behavior of a static library which doesn’t have this limitation, use a static library. There’s no shortage of discussion about this in the CMake issue tracker, so I’ll refer you to go for a search there to find the relevant threads if you want more details on the topic.

2 Likes