cmakedependenciescmake-modules

How do I specify an optional dependency in a CMake package configuration file?


I'm trying to specify correctly the dependencies in the MyLibConfig.cmake file of my project. In CMakeLists.txt I have something like this:

find_package(aLib REQUIRED)
find_package(bLib)

So in MyLibConfig.cmake I wrote something like:

include(CMakeFindDependencyMacro)
find_dependency(aLib REQUIRED)
find_dependency(bLib)

Now, when I write another project that needs myLib, I do:

find_package(MyLib REQUIRED)

This fails because the MyLib configuration file doesn't find bLib, but I would like it to be treated as optional. What is the best Modern CMake practice to handle this?


Solution

  • find_dependency is used only for (initially) REQUIRED packages.

    find_package for non-REQUIRED sub-package remains the same when "copied" into XXXConfig.cmake script.

    For CMakeLists.txt contained

    find_package(aLib REQUIRED)
    find_package(bLib)
    

    corresponded content of MyLibConfig.cmake would be:

    include(CMakeFindDependencyMacro)
    # for REQUIRED package 'find_package' is replaced with 'find_dependency',
    # but 'REQUIRED' keyword is omited.
    find_dependency(aLib)
    # for non-REQUIRED package 'find_package' remains.
    find_package(bLib)
    

    It is important that REQUIRED keyword is NOT passed to the find_dependency macro. So, would one call

    find_package(MyLib) # Without 'REQUIRED'!
    

    and aLib package would be missed, then with (failed) call

    find_dependency(aLib)
    

    CMake would treat MyLib to be missed too (and would print an appropriate message), but won't stop the configuration because of that.