3

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?

rotolof
  • 33
  • 1
  • 3

1 Answers1

4

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.

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
  • Thanks. Since I would like to forward at least the QUIET option, do you think a solution like the following is acceptable? `set(USE_B @USE_B@) # <-- I set this if B_FOUND` `if (USE_B) find_dependency(bLib) endif()` – rotolof Nov 16 '20 at 08:19
  • Yes, if `bLib` is required only for some configuration of your package, then using conditional `find_dependency` is perfectly OK. – Tsyvarev Nov 16 '20 at 08:48