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?
Specify libraries or flags to use when linking a given target and/or its dependents. Usage requirements from linked library targets will be propagated. Usage requirements of a target's dependencies affect compilation of its own sources.
add_library(<name> [STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] [<source>...]) Adds a library target called <name> to be built from the source files listed in the command invocation. The <name> corresponds to the logical target name and must be globally unique within a project.
13 February, 2020. CMake Object Libraries can be used to keep build directories less cluttered and speed up the build process. The traditional workflow for Makefile was to create lots of object files (targets) with the relevant compile options, definitions and link flags.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With