10

I'm attempting to make it easier for other projects to link against the shared libraries we distribute with our project. When I try to take advantage of the EXPORT mechanism, CMake complains that I'm not including the static libraries used to build the shared libraries in the export set. This seems unnecessary to me as the other projects only need to link against the shared library and I don't really want to install the static libraries. This seems to be very similar to this bug, but I might just be misunderstanding how this all works. Here is a minimal example:

CMAKE_MINIMUM_REQUIRED(VERSION 3.2.1) 
PROJECT(ExportTest)

ADD_LIBRARY(myStaticLib STATIC staticLib.c)
ADD_LIBRARY(mySharedLib SHARED sharedLib.c)
TARGET_LINK_LIBRARIES(mySharedLib myStaticLib)

INSTALL(TARGETS mySharedLib EXPORT myExport DESTINATION lib)
INSTALL(EXPORT myExport DESTINATION include)

Which results in the following error message:

CMake Error: install(EXPORT "myExport" ...) includes target "mySharedLib"
which requires target "myStaticLib" that is not in the export set.
rocambille
  • 15,398
  • 12
  • 50
  • 68
rpmcnally
  • 249
  • 2
  • 12
  • Because on Linux, by default a shared lib is not "complete" and when linking an executable with it, the "transitive" static lib is still needed. – André May 17 '21 at 08:11

1 Answers1

7

When using target_link_libraries like you did, library dependencies are transitive by default. Try:

target_link_libraries(mySharedLib PRIVATE myStaticLib)
rocambille
  • 15,398
  • 12
  • 50
  • 68
  • Thanks, that does resolve the error. Could you help me understand why you would you want the static library to be considered a dependency of the shared library? This seems like odd default behavior. – rpmcnally Oct 21 '16 at 19:36
  • `target_link_libraries` does not only manage dependencies for linkage, but also for inclusion. Considering that linking on a static library means the shared library will not include headers of the static one in its public interface is a very strong apriori. Developers of cmake chose to be agnostic on this point, while providing an explicit signature to control the dependency – rocambille Oct 21 '16 at 20:17
  • I got a similar error when trying to link an object library to a static library. However, installing the object library target to the export without specifying a destination (which you would do with the OBJECTS argument to the install command) installs the object library as an interface library. No objects actually get installed, but this is sufficient to resolve transitive usage requirements. See the end of this section in the [docs](https://cmake.org/cmake/help/latest/command/install.html#installing-targets) – jezza Jan 24 '21 at 11:14