Installing a CMake library: also ship find modules for the dependencies?

Viewed 1209

My CMake library, MyLibrary, has a dependency for OtherLibrary, that I import with a non-standard FindOtherLibrary.cmake.

My library depends on OtherLibrary publicly:

target_link_libraries(MyLibrary PUBLIC OtherLibrary::OtherLibrary)

When I install MyLibrary (together with MyLibraryConfig.cmake), and users want to link against it, they therefore need to import OtherLibrary.

Is there a good practice regarding how to distribute FindOtherLibrary.cmake along MyLibrary?


Ideally, one could make things even easier for users of MyLibrary by importing OtherLibrary automatically from the installed config file MyLibraryConfig.cmake, if it contains something like

include(CMakeFindDependencyMacro)
find_dependency(OtherLibrary)

and knows where FindOtherLibrary.cmake is.

Is this at all possible?

2 Answers

I ended up finding a solution to my question.

In principle, it does what @utopia suggested, but in an automated fashion: the end user of my library does not need to set up (or even know about) FindOtherLibrary.cmake. It will be imported automatically by MyLibraryConfig.cmake.

To do so, I install FindOtherLibrary.cmake along MyLibraryConfig.cmake:

install(FILES
          /path/to/MyLibraryConfig.cmake
        DESTINATION
          lib/cmake/MyLibrary
        )
install(FILES
          /path/to/FindOtherLibrary.cmake
        DESTINATION
          lib/cmake/MyLibrary/Modules
        )

And in MyLibraryConfig.cmake I set up how to import it:

include(CMakeFindDependencyMacro)
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_LIST_DIR}/Modules/")
find_dependency(OtherLibrary REQUIRED)

Note that I set the variable CMAKE_MODULE_PATH because it is not possible to specify the location of find modules in find_package or find_dependency (works only for config mode).

Related