27

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?

plasmacel
  • 8,183
  • 7
  • 53
  • 101
tamas.kenez
  • 7,301
  • 4
  • 24
  • 34
  • What do you recommend instead? There's a library, consists of about ten separate modules, some of them implementing the exported functions/classes, the whole thing compiled both as static and as shared. Put all the sources directly in one single library target? – tamas.kenez Jul 17 '15 at 22:40
  • 2
    If I specify my modules as object libs its easier to specify per-module properties, like each module can have its own set of include dirs, definitions. Their files get automatically separated in the IDE. Of course I could get by without object libs but it's somewhat better than all-sources-in-one-lib in every aspect. – tamas.kenez Jul 17 '15 at 23:11
  • Yes, using regular lib target for each module would be the best and that was the case until last week. But I needed an easy way to compile them into a single dll. Object lib was the easiest. The alternatives: http://stackoverflow.com/questions/5136184/linking-windows-dll-files-from-static-libraries-using-cmake-without-hand-craftin – tamas.kenez Jul 17 '15 at 23:48
  • 7
    Did you eventually find a solution you were happy with? If so, I'd be very interested in hearing about it. – Parker Coates Jan 27 '16 at 16:34
  • 2
    [upstream issue](https://gitlab.kitware.com/cmake/cmake/issues/14778) – Darklighter Oct 15 '17 at 03:08

1 Answers1

20

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)
ian5v
  • 2,078
  • 2
  • 18
  • 20