tamas.kenez
tamas.kenez

Reputation: 7799

How to specify imported dependencies of an OBJECT library?

I have an OBJECT library objlib which is linked into the main target maintarget. The objlib has a dependent library, say, ZLIB. If we're using the legacy <package-name>_* variables then it's easy:

add_library(objlib OBJECT ...)
target_include_directories(objlib ${ZLIB_INCLUDE_DIRS})
...
add_executable(maintarget $<TARGET_OBJECTS:objlib>)
target_link_libraries(maintarget ${ZLIB_LIBRARIES})

But I want to use the dependency as an IMPORTED library because it's more concise (and the convenient way to create config modules, that is, using install(EXPORT ...), does just that).

The following code does not work because target_link_libraries cannot be used with an OBJECT library:

add_library(objlib OBJECT ...)
target_link_libraries(objlib ZLIB::ZLIB)

Linking ZLIB::ZLIB to maintarget does not work either, objlib does not get the include directories:

add_library(objlib OBJECT ...)
...
add_executable(maintarget $<TARGET_OBJECTS:objlib>)
target_link_libraries(maintarget ZLIB::ZLIB)

Hacking with an intermediate INTERFACE library (objlib-wrapper) does not work either.

The only thing that works is to query the IMPORTED library's properties and regenerate the information normally available in the <package-name>_* variables. Which is a nasty workaround.

Is there a better way?

Upvotes: 27

Views: 7738

Answers (1)

ian5v
ian5v

Reputation: 2118

As of CMake 3.12, you can now use target_link_libraries on object libraries to get usage requirements.

Using 3.12, this approach that you mentioned should work:

add_library(objlib OBJECT ...)
target_link_libraries(objlib ZLIB::ZLIB)

Upvotes: 20

Related Questions