CMakePackageConfigHelpers.cmake 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file Copyright.txt or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. CMakePackageConfigHelpers
  5. -------------------------
  6. Helpers functions for creating config files that can be included by other
  7. projects to find and use a package.
  8. Adds the :command:`configure_package_config_file()` and
  9. :command:`write_basic_package_version_file()` commands.
  10. Generating a Package Configuration File
  11. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  12. .. command:: configure_package_config_file
  13. Create a config file for a project::
  14. configure_package_config_file(<input> <output>
  15. INSTALL_DESTINATION <path>
  16. [PATH_VARS <var1> <var2> ... <varN>]
  17. [NO_SET_AND_CHECK_MACRO]
  18. [NO_CHECK_REQUIRED_COMPONENTS_MACRO]
  19. [INSTALL_PREFIX <path>]
  20. )
  21. ``configure_package_config_file()`` should be used instead of the plain
  22. :command:`configure_file()` command when creating the ``<PackageName>Config.cmake``
  23. or ``<PackageName>-config.cmake`` file for installing a project or library.
  24. It helps making the resulting package relocatable by avoiding hardcoded paths
  25. in the installed ``Config.cmake`` file.
  26. In a ``FooConfig.cmake`` file there may be code like this to make the install
  27. destinations know to the using project:
  28. .. code-block:: cmake
  29. set(FOO_INCLUDE_DIR "@CMAKE_INSTALL_FULL_INCLUDEDIR@" )
  30. set(FOO_DATA_DIR "@CMAKE_INSTALL_PREFIX@/@RELATIVE_DATA_INSTALL_DIR@" )
  31. set(FOO_ICONS_DIR "@CMAKE_INSTALL_PREFIX@/share/icons" )
  32. #...logic to determine installedPrefix from the own location...
  33. set(FOO_CONFIG_DIR "${installedPrefix}/@CONFIG_INSTALL_DIR@" )
  34. All 4 options shown above are not sufficient, since the first 3 hardcode the
  35. absolute directory locations, and the 4th case works only if the logic to
  36. determine the ``installedPrefix`` is correct, and if ``CONFIG_INSTALL_DIR``
  37. contains a relative path, which in general cannot be guaranteed. This has the
  38. effect that the resulting ``FooConfig.cmake`` file would work poorly under
  39. Windows and OSX, where users are used to choose the install location of a
  40. binary package at install time, independent from how
  41. :variable:`CMAKE_INSTALL_PREFIX` was set at build/cmake time.
  42. Using ``configure_package_config_file`` helps. If used correctly, it makes
  43. the resulting ``FooConfig.cmake`` file relocatable. Usage:
  44. 1. write a ``FooConfig.cmake.in`` file as you are used to
  45. 2. insert a line containing only the string ``@PACKAGE_INIT@``
  46. 3. instead of ``set(FOO_DIR "@SOME_INSTALL_DIR@")``, use
  47. ``set(FOO_DIR "@PACKAGE_SOME_INSTALL_DIR@")`` (this must be after the
  48. ``@PACKAGE_INIT@`` line)
  49. 4. instead of using the normal :command:`configure_file()`, use
  50. ``configure_package_config_file()``
  51. The ``<input>`` and ``<output>`` arguments are the input and output file, the
  52. same way as in :command:`configure_file()`.
  53. The ``<path>`` given to ``INSTALL_DESTINATION`` must be the destination where
  54. the ``FooConfig.cmake`` file will be installed to. This path can either be
  55. absolute, or relative to the ``INSTALL_PREFIX`` path.
  56. The variables ``<var1>`` to ``<varN>`` given as ``PATH_VARS`` are the
  57. variables which contain install destinations. For each of them the macro will
  58. create a helper variable ``PACKAGE_<var...>``. These helper variables must be
  59. used in the ``FooConfig.cmake.in`` file for setting the installed location.
  60. They are calculated by ``configure_package_config_file`` so that they are
  61. always relative to the installed location of the package. This works both for
  62. relative and also for absolute locations. For absolute locations it works
  63. only if the absolute location is a subdirectory of ``INSTALL_PREFIX``.
  64. .. versionadded:: 3.1
  65. If the ``INSTALL_PREFIX`` argument is passed, this is used as base path to
  66. calculate all the relative paths. The ``<path>`` argument must be an absolute
  67. path. If this argument is not passed, the :variable:`CMAKE_INSTALL_PREFIX`
  68. variable will be used instead. The default value is good when generating a
  69. FooConfig.cmake file to use your package from the install tree. When
  70. generating a FooConfig.cmake file to use your package from the build tree this
  71. option should be used.
  72. By default ``configure_package_config_file`` also generates two helper macros,
  73. ``set_and_check()`` and ``check_required_components()`` into the
  74. ``FooConfig.cmake`` file.
  75. ``set_and_check()`` should be used instead of the normal ``set()`` command for
  76. setting directories and file locations. Additionally to setting the variable
  77. it also checks that the referenced file or directory actually exists and fails
  78. with a ``FATAL_ERROR`` otherwise. This makes sure that the created
  79. ``FooConfig.cmake`` file does not contain wrong references.
  80. When using the ``NO_SET_AND_CHECK_MACRO``, this macro is not generated
  81. into the ``FooConfig.cmake`` file.
  82. ``check_required_components(<PackageName>)`` should be called at the end of
  83. the ``FooConfig.cmake`` file. This macro checks whether all requested,
  84. non-optional components have been found, and if this is not the case, sets
  85. the ``Foo_FOUND`` variable to ``FALSE``, so that the package is considered to
  86. be not found. It does that by testing the ``Foo_<Component>_FOUND``
  87. variables for all requested required components. This macro should be
  88. called even if the package doesn't provide any components to make sure
  89. users are not specifying components erroneously. When using the
  90. ``NO_CHECK_REQUIRED_COMPONENTS_MACRO`` option, this macro is not generated
  91. into the ``FooConfig.cmake`` file.
  92. For an example see below the documentation for
  93. :command:`write_basic_package_version_file()`.
  94. Generating a Package Version File
  95. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  96. .. command:: write_basic_package_version_file
  97. Create a version file for a project::
  98. write_basic_package_version_file(<filename>
  99. [VERSION <major.minor.patch>]
  100. COMPATIBILITY <AnyNewerVersion|SameMajorVersion|SameMinorVersion|ExactVersion>
  101. [ARCH_INDEPENDENT] )
  102. Writes a file for use as ``<PackageName>ConfigVersion.cmake`` file to
  103. ``<filename>``. See the documentation of :command:`find_package()` for
  104. details on this.
  105. ``<filename>`` is the output filename, it should be in the build tree.
  106. ``<major.minor.patch>`` is the version number of the project to be installed.
  107. If no ``VERSION`` is given, the :variable:`PROJECT_VERSION` variable is used.
  108. If this hasn't been set, it errors out.
  109. The ``COMPATIBILITY`` mode ``AnyNewerVersion`` means that the installed
  110. package version will be considered compatible if it is newer or exactly the
  111. same as the requested version. This mode should be used for packages which
  112. are fully backward compatible, also across major versions.
  113. If ``SameMajorVersion`` is used instead, then the behavior differs from
  114. ``AnyNewerVersion`` in that the major version number must be the same as
  115. requested, e.g. version 2.0 will not be considered compatible if 1.0 is
  116. requested. This mode should be used for packages which guarantee backward
  117. compatibility within the same major version.
  118. If ``SameMinorVersion`` is used, the behavior is the same as
  119. ``SameMajorVersion``, but both major and minor version must be the same as
  120. requested, e.g version 0.2 will not be compatible if 0.1 is requested.
  121. If ``ExactVersion`` is used, then the package is only considered compatible if
  122. the requested version matches exactly its own version number (not considering
  123. the tweak version). For example, version 1.2.3 of a package is only
  124. considered compatible to requested version 1.2.3. This mode is for packages
  125. without compatibility guarantees.
  126. If your project has more elaborated version matching rules, you will need to
  127. write your own custom ``ConfigVersion.cmake`` file instead of using this
  128. macro.
  129. .. versionadded:: 3.11
  130. The ``SameMinorVersion`` compatibility mode.
  131. .. versionadded:: 3.14
  132. If ``ARCH_INDEPENDENT`` is given, the installed package version will be
  133. considered compatible even if it was built for a different architecture than
  134. the requested architecture. Otherwise, an architecture check will be performed,
  135. and the package will be considered compatible only if the architecture matches
  136. exactly. For example, if the package is built for a 32-bit architecture, the
  137. package is only considered compatible if it is used on a 32-bit architecture,
  138. unless ``ARCH_INDEPENDENT`` is given, in which case the package is considered
  139. compatible on any architecture.
  140. .. note:: ``ARCH_INDEPENDENT`` is intended for header-only libraries or similar
  141. packages with no binaries.
  142. .. versionadded:: 3.19
  143. The version file generated by ``AnyNewerVersion``, ``SameMajorVersion`` and
  144. ``SameMinorVersion`` arguments of ``COMPATIBILITY`` handle the version range
  145. if any is specified (see :command:`find_package` command for the details).
  146. ``ExactVersion`` mode is incompatible with version ranges and will display an
  147. author warning if one is specified.
  148. Internally, this macro executes :command:`configure_file()` to create the
  149. resulting version file. Depending on the ``COMPATIBILITY``, the corresponding
  150. ``BasicConfigVersion-<COMPATIBILITY>.cmake.in`` file is used.
  151. Please note that these files are internal to CMake and you should not call
  152. :command:`configure_file()` on them yourself, but they can be used as starting
  153. point to create more sophisticted custom ``ConfigVersion.cmake`` files.
  154. Example Generating Package Files
  155. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  156. Example using both :command:`configure_package_config_file` and
  157. ``write_basic_package_version_file()``:
  158. ``CMakeLists.txt``:
  159. .. code-block:: cmake
  160. include(GNUInstallDirs)
  161. set(INCLUDE_INSTALL_DIR ${CMAKE_INSTALL_INCLUDEDIR}/Foo
  162. CACHE PATH "Location of header files" )
  163. set(SYSCONFIG_INSTALL_DIR ${CMAKE_INSTALL_SYSCONFDIR}/foo
  164. CACHE PATH "Location of configuration files" )
  165. #...
  166. include(CMakePackageConfigHelpers)
  167. configure_package_config_file(FooConfig.cmake.in
  168. ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
  169. INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Foo
  170. PATH_VARS INCLUDE_INSTALL_DIR SYSCONFIG_INSTALL_DIR)
  171. write_basic_package_version_file(
  172. ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
  173. VERSION 1.2.3
  174. COMPATIBILITY SameMajorVersion )
  175. install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
  176. ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
  177. DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Foo )
  178. ``FooConfig.cmake.in``:
  179. ::
  180. set(FOO_VERSION x.y.z)
  181. ...
  182. @PACKAGE_INIT@
  183. ...
  184. set_and_check(FOO_INCLUDE_DIR "@PACKAGE_INCLUDE_INSTALL_DIR@")
  185. set_and_check(FOO_SYSCONFIG_DIR "@PACKAGE_SYSCONFIG_INSTALL_DIR@")
  186. check_required_components(Foo)
  187. #]=======================================================================]
  188. include(WriteBasicConfigVersionFile)
  189. macro(WRITE_BASIC_PACKAGE_VERSION_FILE)
  190. write_basic_config_version_file(${ARGN})
  191. endmacro()
  192. function(CONFIGURE_PACKAGE_CONFIG_FILE _inputFile _outputFile)
  193. set(options NO_SET_AND_CHECK_MACRO NO_CHECK_REQUIRED_COMPONENTS_MACRO)
  194. set(oneValueArgs INSTALL_DESTINATION INSTALL_PREFIX)
  195. set(multiValueArgs PATH_VARS )
  196. cmake_parse_arguments(CCF "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
  197. if(CCF_UNPARSED_ARGUMENTS)
  198. message(FATAL_ERROR "Unknown keywords given to CONFIGURE_PACKAGE_CONFIG_FILE(): \"${CCF_UNPARSED_ARGUMENTS}\"")
  199. endif()
  200. if(NOT CCF_INSTALL_DESTINATION)
  201. message(FATAL_ERROR "No INSTALL_DESTINATION given to CONFIGURE_PACKAGE_CONFIG_FILE()")
  202. endif()
  203. if(DEFINED CCF_INSTALL_PREFIX)
  204. if(IS_ABSOLUTE "${CCF_INSTALL_PREFIX}")
  205. set(installPrefix "${CCF_INSTALL_PREFIX}")
  206. else()
  207. message(FATAL_ERROR "INSTALL_PREFIX must be an absolute path")
  208. endif()
  209. elseif(IS_ABSOLUTE "${CMAKE_INSTALL_PREFIX}")
  210. set(installPrefix "${CMAKE_INSTALL_PREFIX}")
  211. else()
  212. get_filename_component(installPrefix "${CMAKE_INSTALL_PREFIX}" ABSOLUTE)
  213. endif()
  214. if(IS_ABSOLUTE "${CCF_INSTALL_DESTINATION}")
  215. set(absInstallDir "${CCF_INSTALL_DESTINATION}")
  216. else()
  217. set(absInstallDir "${installPrefix}/${CCF_INSTALL_DESTINATION}")
  218. endif()
  219. file(RELATIVE_PATH PACKAGE_RELATIVE_PATH "${absInstallDir}" "${installPrefix}" )
  220. foreach(var ${CCF_PATH_VARS})
  221. if(NOT DEFINED ${var})
  222. message(FATAL_ERROR "Variable ${var} does not exist")
  223. else()
  224. if(IS_ABSOLUTE "${${var}}")
  225. string(REPLACE "${installPrefix}" "\${PACKAGE_PREFIX_DIR}"
  226. PACKAGE_${var} "${${var}}")
  227. else()
  228. set(PACKAGE_${var} "\${PACKAGE_PREFIX_DIR}/${${var}}")
  229. endif()
  230. endif()
  231. endforeach()
  232. get_filename_component(inputFileName "${_inputFile}" NAME)
  233. set(PACKAGE_INIT "
  234. ####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() #######
  235. ####### Any changes to this file will be overwritten by the next CMake run ####
  236. ####### The input file was ${inputFileName} ########
  237. get_filename_component(PACKAGE_PREFIX_DIR \"\${CMAKE_CURRENT_LIST_DIR}/${PACKAGE_RELATIVE_PATH}\" ABSOLUTE)
  238. ")
  239. if("${absInstallDir}" MATCHES "^(/usr)?/lib(64)?/.+")
  240. # Handle "/usr move" symlinks created by some Linux distros.
  241. string(APPEND PACKAGE_INIT "
  242. # Use original install prefix when loaded through a \"/usr move\"
  243. # cross-prefix symbolic link such as /lib -> /usr/lib.
  244. get_filename_component(_realCurr \"\${CMAKE_CURRENT_LIST_DIR}\" REALPATH)
  245. get_filename_component(_realOrig \"${absInstallDir}\" REALPATH)
  246. if(_realCurr STREQUAL _realOrig)
  247. set(PACKAGE_PREFIX_DIR \"${installPrefix}\")
  248. endif()
  249. unset(_realOrig)
  250. unset(_realCurr)
  251. ")
  252. endif()
  253. if(NOT CCF_NO_SET_AND_CHECK_MACRO)
  254. string(APPEND PACKAGE_INIT "
  255. macro(set_and_check _var _file)
  256. set(\${_var} \"\${_file}\")
  257. if(NOT EXISTS \"\${_file}\")
  258. message(FATAL_ERROR \"File or directory \${_file} referenced by variable \${_var} does not exist !\")
  259. endif()
  260. endmacro()
  261. ")
  262. endif()
  263. if(NOT CCF_NO_CHECK_REQUIRED_COMPONENTS_MACRO)
  264. string(APPEND PACKAGE_INIT "
  265. macro(check_required_components _NAME)
  266. foreach(comp \${\${_NAME}_FIND_COMPONENTS})
  267. if(NOT \${_NAME}_\${comp}_FOUND)
  268. if(\${_NAME}_FIND_REQUIRED_\${comp})
  269. set(\${_NAME}_FOUND FALSE)
  270. endif()
  271. endif()
  272. endforeach()
  273. endmacro()
  274. ")
  275. endif()
  276. string(APPEND PACKAGE_INIT "
  277. ####################################################################################")
  278. configure_file("${_inputFile}" "${_outputFile}" @ONLY)
  279. endfunction()