[CMake] Not being able to create a 'link' interface for an OBJECT library

Jakob van Bethlehem jsvanbethlehem at gmail.com
Mon Jan 30 05:04:41 EST 2017


Dear all,

Recently I read the excellent tip of creating a 'link interface' for an
OBJECT library in order to overcome the inability to directly link an
OBJECT library, see:
https://cmake.org/cmake/help/v3.5/manual/cmake-buildsystem.7.html#object-libraries

This sounded like a perfect idea, so I tried it out on Windows 7 with the
VS 2013 64bit generator.
The first step was to build a shared library out of an object library,
which worked like a charm:

====
## Setup OBJECT library and a 'object link interface'
add_library(MyLib.Object OBJECT
  ... sources ..
)
target_include_directories(MyLib.Object
  PUBLIC
    .... includes
)

add_library(MyLib.Object.LinkInterface INTERFACE)
target_sources(MyLib.Object.LinkInterface INTERFACE
$<TARGET_OBJECTS:MyLib.Object>)
target_include_directories(MyLib.Object.LinkInterface
  INTERFACE $<TARGET_PROPERTY:MyLib.Object,INTERFACE_INCLUDE_DIRECTORIES>
)
target_link_libraries(MyLib.Object.LinkInterface
  INTERFACE
    .... some dependent libraries
)

## set up shared library:
add_library(MyLib SHARED
  .. some additional sources
)

target_link_libraries(MyLib
  PUBLIC
    MyLib.Object.LinkInterface
)
====

The second step was to try to create an executable that links with the
shared library. That is were I ran into some problems I can't quite fathom:
====
add_executable(MyExe
  ... sources ...
)

target_link_libraries(MyExe
  MyLib
)
====

This results in the following error from CMake:
CMake Error at MyExe/CMakeLists.txt:16 (add_executable):
  Cannot find source file:


<MyLibPath>/InstrumentControl.Object.dir/$(Configuration)/InstrumentControl.obj

  Tried extensions .c .C .c++ .cc .cpp .cxx .m .M .mm .h .hh .h++ .hm .hpp
  .hxx .in .txx

It seems that for some reason CMake is trying to reuse the same target
sources on the executable, which doesn't make any sense really, as I'm
trying to link against a normal shared library.

The solution is to remove the 'target_sources' and put the
$<TARGET_OBJECTS:..> directly as a source when creating the shared library.
That is quite unfortunate however. The entire
purpose of the 'object link interface' was to remove the need to put these
generator expressions where there are needed, as explained on the
documentation page I referred to above.

So, the questions I have:
- should the described procedure work?
- if yes, did I something wrong, or did I stumble across a CMake bug?
- if no, it makes sense to put in a very clear warning on the referred
webpage, that the 'trick' will *not* work if one ever tries to link against
the final library...... ajjjj


Sincerely,
Jakob
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://public.kitware.com/pipermail/cmake/attachments/20170130/0965e9ba/attachment-0001.html>


More information about the CMake mailing list