Joel Bodenmann
Joel Bodenmann

Reputation: 2282

CMake object library target usage syntax

The cmake documentation on object libraries states that (other) targets may reference an object library using the $<objlib> syntax (where objlib is the name of the object library):

add_library(foo OBJECT 
  foo.cpp
)

add_library(bar SHARED 
  bar.cpp
  $<TARGET_OBJECTS:foo>
)

I would like to understand what the reason for the existence & need of the TARGET_OBJECTS:foo generator expression is? What exactly prevents cmake from being able to handle just this case:

add_library(foo OBJECT 
  foo.cpp
)

add_library(bar SHARED 
  bar.cpp
  foo
)

Upvotes: 1

Views: 1280

Answers (1)

nickelpro
nickelpro

Reputation: 2917

add_library requires you to list the files required for the linker to build your library. Since you're using an object library, there's no final object for foo to refer to, just a collection of objects.

Imagine a slightly more complex scenario:

add_library(foo OBJECT 
  fooA.cpp
  fooB.cpp
)

add_library(bar SHARED 
  barA.cpp
  barB.cpp
)

add_library(spaz SHARED
  foo
  bar
)

For the spaz directive, bar refers to a single bar.so (or DLL or whatever) that was linked by the respective add_library, but what does foo refer to? There's two files, fooA.o and fooB.o, and so cmake needs to use a generator expression to collect these.

I'm not certain if there's a technical reason that cmake can't support a shorthand for object libraries, but the current solution leverages the already existing generator expressions.

Upvotes: 1

Related Questions