cmake

Hinting Find<name>.cmake Files with a custom directory


In CMake, is there a way to make built-in Find scripts to prioritize a custom directory that we specify? Because especially in windows, module finding scripts usually can't detect the module in, for example visual studio directories. Therefore I usually have to manually set the paths for the external libraries which is pretty tiring. Instead, I want those scripts to look in a custom directory, let's say 'dependencies' folder in the main project first so that I can directly put those externals in that folder which is much easier than putting them into the VC folder or manually setting the paths.


Solution

  • Setting CMAKE_PREFIX_PATH variable serves exactly these purposes: hinting find_* function about location of searched item.

    While description of this variable doesn't note about find_package function, the variable affects it indirectly: the most of Find<name>.cmake scripts use find_library and find_path functions. Note, that all find_* functions have precise algorithm for search items, and paths constructed with CMAKE_PREFIX_PATH are checked before system ones.

    Moreover, CMAKE_PREFIX_PATH affects some other search procedures. E.g., if 3rd party package provides <name>Config.cmake script instead of Find<name>.cmake one, this script is also searched for using this variable. pkg_check_modules also uses CMAKE_PREFIX_PATH to search for .pc files describing the package.

    CMAKE_PREFIX_PATH variable can be set as environment one (in platform-depending and usage-specific way), as parameter to cmake call:

    cmake -DCMAKE_PREFIX_PATH=<additional-path> <other-parameters>
    

    or within CMakeLists.txt file. In the last case it is better to append search directories, so user of your package will be able to set the variable too, for search packages not shipped with your project:

    list(APPEND CMAKE_PREFIX_PATH "${CMAKE_SOURCE_DIR}/dependencies")
    

    Note, that variable CMAKE_PREFIX_PATH doesn't affect searching for FindXXX.cmake script itself. For specifying the directory where the script is located, use CMAKE_MODULE_PATH variable.