Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

cmake - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...