How to conditionally call either `find_pacakge()` or `find_dependency()`?

We have a library that depends on various third-party libraries. These dependencies are generally found using find_package in the project’s main CMake file.

To avoid having to write these dependencies twice, in the main CMake file and the project’s -config.cmake file, I have separated these find_package() calls in a separate ExternalDependencies.cmake file that contains all find_package() calls. This file is installed and included both from the project’s CMake file and from the -config.cmake file.

Now I would like to call find_package() for these external dependencies when building the library itself, but in case the library is found is a dependency of some other CMake project, find_dependency() should be used. What is the recommended approach to determine which version of the two to use?

FWIW, this is the current approach I am using from within ExternalDependencies.cmake; it is quite ugly:

if(PROJECT_NAME STREQUAL "MyLib")
  macro(_find_package)
    find_package(${ARGN})
  endmacro()
else()
  include(CMakeFindDependencyMacro)

  macro(_find_package)
    find_dependency(${ARGN})
  endmacro()
endif()

_find_package(...)

Finally, for some of the external dependencies, find modules are not available, and we have to resort to pkg_check_modules(). I assume there is no find_dependency()-like approach for pkg_check_modules() to be used from config files?

Hello, you may try to check the existence of $CMAKE_FIND_PACKAGE_NAME and if it exists (and equals to your package name), then you should use find_dependency(), otherwise, find_package().

All list of these magic variables defined in scope of your package is defined here: https://cmake.org/cmake/help/latest/command/find_package.html#id11

1 Like

Thanks Alex, that sounds like a good approach.

1 Like