CMakePackageConfigHelpers.cmake 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. If the ``INSTALL_PREFIX`` argument is passed, this is used as base path to
  65. calculate all the relative paths. The ``<path>`` argument must be an absolute
  66. path. If this argument is not passed, the :variable:`CMAKE_INSTALL_PREFIX`
  67. variable will be used instead. The default value is good when generating a
  68. FooConfig.cmake file to use your package from the install tree. When
  69. generating a FooConfig.cmake file to use your package from the build tree this
  70. option should be used.
  71. By default ``configure_package_config_file`` also generates two helper macros,
  72. ``set_and_check()`` and ``check_required_components()`` into the
  73. ``FooConfig.cmake`` file.
  74. ``set_and_check()`` should be used instead of the normal ``set()`` command for
  75. setting directories and file locations. Additionally to setting the variable
  76. it also checks that the referenced file or directory actually exists and fails
  77. with a ``FATAL_ERROR`` otherwise. This makes sure that the created
  78. ``FooConfig.cmake`` file does not contain wrong references.
  79. When using the ``NO_SET_AND_CHECK_MACRO``, this macro is not generated
  80. into the ``FooConfig.cmake`` file.
  81. ``check_required_components(<PackageName>)`` should be called at the end of
  82. the ``FooConfig.cmake`` file. This macro checks whether all requested,
  83. non-optional components have been found, and if this is not the case, sets
  84. the ``Foo_FOUND`` variable to ``FALSE``, so that the package is considered to
  85. be not found. It does that by testing the ``Foo_<Component>_FOUND``
  86. variables for all requested required components. This macro should be
  87. called even if the package doesn't provide any components to make sure
  88. users are not specifying components erroneously. When using the
  89. ``NO_CHECK_REQUIRED_COMPONENTS_MACRO`` option, this macro is not generated
  90. into the ``FooConfig.cmake`` file.
  91. For an example see below the documentation for
  92. :command:`write_basic_package_version_file()`.
  93. Generating a Package Version File
  94. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  95. .. command:: write_basic_package_version_file
  96. Create a version file for a project::
  97. write_basic_package_version_file(<filename>
  98. [VERSION <major.minor.patch>]
  99. COMPATIBILITY <AnyNewerVersion|SameMajorVersion|SameMinorVersion|ExactVersion>
  100. [ARCH_INDEPENDENT] )
  101. Writes a file for use as ``<PackageName>ConfigVersion.cmake`` file to
  102. ``<filename>``. See the documentation of :command:`find_package()` for
  103. details on this.
  104. ``<filename>`` is the output filename, it should be in the build tree.
  105. ``<major.minor.patch>`` is the version number of the project to be installed.
  106. If no ``VERSION`` is given, the :variable:`PROJECT_VERSION` variable is used.
  107. If this hasn't been set, it errors out.
  108. The ``COMPATIBILITY`` mode ``AnyNewerVersion`` means that the installed
  109. package version will be considered compatible if it is newer or exactly the
  110. same as the requested version. This mode should be used for packages which
  111. are fully backward compatible, also across major versions.
  112. If ``SameMajorVersion`` is used instead, then the behaviour differs from
  113. ``AnyNewerVersion`` in that the major version number must be the same as
  114. requested, e.g. version 2.0 will not be considered compatible if 1.0 is
  115. requested. This mode should be used for packages which guarantee backward
  116. compatibility within the same major version.
  117. If ``SameMinorVersion`` is used, the behaviour is the same as
  118. ``SameMajorVersion``, but both major and minor version must be the same as
  119. requested, e.g version 0.2 will not be compatible if 0.1 is requested.
  120. If ``ExactVersion`` is used, then the package is only considered compatible if
  121. the requested version matches exactly its own version number (not considering
  122. the tweak version). For example, version 1.2.3 of a package is only
  123. considered compatible to requested version 1.2.3. This mode is for packages
  124. without compatibility guarantees.
  125. If your project has more elaborated version matching rules, you will need to
  126. write your own custom ``ConfigVersion.cmake`` file instead of using this
  127. macro.
  128. If ``ARCH_INDEPENDENT`` is given, the installed package version will be
  129. considered compatible even if it was built for a different architecture than
  130. the requested architecture. Otherwise, an architecture check will be performed,
  131. and the package will be considered compatible only if the architecture matches
  132. exactly. For example, if the package is built for a 32-bit architecture, the
  133. package is only considered compatible if it is used on a 32-bit architecture,
  134. unless ``ARCH_INDEPENDENT`` is given, in which case the package is considered
  135. compatible on any architecture.
  136. .. note:: ``ARCH_INDEPENDENT`` is intended for header-only libraries or similar
  137. packages with no binaries.
  138. Internally, this macro executes :command:`configure_file()` to create the
  139. resulting version file. Depending on the ``COMPATIBILITY``, the corresponding
  140. ``BasicConfigVersion-<COMPATIBILITY>.cmake.in`` file is used.
  141. Please note that these files are internal to CMake and you should not call
  142. :command:`configure_file()` on them yourself, but they can be used as starting
  143. point to create more sophisticted custom ``ConfigVersion.cmake`` files.
  144. Example Generating Package Files
  145. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  146. Example using both :command:`configure_package_config_file` and
  147. ``write_basic_package_version_file()``:
  148. ``CMakeLists.txt``:
  149. .. code-block:: cmake
  150. set(INCLUDE_INSTALL_DIR include/ ... CACHE )
  151. set(LIB_INSTALL_DIR lib/ ... CACHE )
  152. set(SYSCONFIG_INSTALL_DIR etc/foo/ ... CACHE )
  153. #...
  154. include(CMakePackageConfigHelpers)
  155. configure_package_config_file(FooConfig.cmake.in
  156. ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
  157. INSTALL_DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake
  158. PATH_VARS INCLUDE_INSTALL_DIR SYSCONFIG_INSTALL_DIR)
  159. write_basic_package_version_file(
  160. ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
  161. VERSION 1.2.3
  162. COMPATIBILITY SameMajorVersion )
  163. install(FILES ${CMAKE_CURRENT_BINARY_DIR}/FooConfig.cmake
  164. ${CMAKE_CURRENT_BINARY_DIR}/FooConfigVersion.cmake
  165. DESTINATION ${LIB_INSTALL_DIR}/Foo/cmake )
  166. ``FooConfig.cmake.in``:
  167. ::
  168. set(FOO_VERSION x.y.z)
  169. ...
  170. @PACKAGE_INIT@
  171. ...
  172. set_and_check(FOO_INCLUDE_DIR "@PACKAGE_INCLUDE_INSTALL_DIR@")
  173. set_and_check(FOO_SYSCONFIG_DIR "@PACKAGE_SYSCONFIG_INSTALL_DIR@")
  174. check_required_components(Foo)
  175. #]=======================================================================]
  176. include(WriteBasicConfigVersionFile)
  177. macro(WRITE_BASIC_PACKAGE_VERSION_FILE)
  178. write_basic_config_version_file(${ARGN})
  179. endmacro()
  180. function(CONFIGURE_PACKAGE_CONFIG_FILE _inputFile _outputFile)
  181. set(options NO_SET_AND_CHECK_MACRO NO_CHECK_REQUIRED_COMPONENTS_MACRO)
  182. set(oneValueArgs INSTALL_DESTINATION INSTALL_PREFIX)
  183. set(multiValueArgs PATH_VARS )
  184. cmake_parse_arguments(CCF "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
  185. if(CCF_UNPARSED_ARGUMENTS)
  186. message(FATAL_ERROR "Unknown keywords given to CONFIGURE_PACKAGE_CONFIG_FILE(): \"${CCF_UNPARSED_ARGUMENTS}\"")
  187. endif()
  188. if(NOT CCF_INSTALL_DESTINATION)
  189. message(FATAL_ERROR "No INSTALL_DESTINATION given to CONFIGURE_PACKAGE_CONFIG_FILE()")
  190. endif()
  191. if(DEFINED CCF_INSTALL_PREFIX)
  192. if(IS_ABSOLUTE "${CCF_INSTALL_PREFIX}")
  193. set(installPrefix "${CCF_INSTALL_PREFIX}")
  194. else()
  195. message(FATAL_ERROR "INSTALL_PREFIX must be an absolute path")
  196. endif()
  197. elseif(IS_ABSOLUTE "${CMAKE_INSTALL_PREFIX}")
  198. set(installPrefix "${CMAKE_INSTALL_PREFIX}")
  199. else()
  200. get_filename_component(installPrefix "${CMAKE_INSTALL_PREFIX}" ABSOLUTE)
  201. endif()
  202. if(IS_ABSOLUTE "${CCF_INSTALL_DESTINATION}")
  203. set(absInstallDir "${CCF_INSTALL_DESTINATION}")
  204. else()
  205. set(absInstallDir "${installPrefix}/${CCF_INSTALL_DESTINATION}")
  206. endif()
  207. file(RELATIVE_PATH PACKAGE_RELATIVE_PATH "${absInstallDir}" "${installPrefix}" )
  208. foreach(var ${CCF_PATH_VARS})
  209. if(NOT DEFINED ${var})
  210. message(FATAL_ERROR "Variable ${var} does not exist")
  211. else()
  212. if(IS_ABSOLUTE "${${var}}")
  213. string(REPLACE "${installPrefix}" "\${PACKAGE_PREFIX_DIR}"
  214. PACKAGE_${var} "${${var}}")
  215. else()
  216. set(PACKAGE_${var} "\${PACKAGE_PREFIX_DIR}/${${var}}")
  217. endif()
  218. endif()
  219. endforeach()
  220. get_filename_component(inputFileName "${_inputFile}" NAME)
  221. set(PACKAGE_INIT "
  222. ####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() #######
  223. ####### Any changes to this file will be overwritten by the next CMake run ####
  224. ####### The input file was ${inputFileName} ########
  225. get_filename_component(PACKAGE_PREFIX_DIR \"\${CMAKE_CURRENT_LIST_DIR}/${PACKAGE_RELATIVE_PATH}\" ABSOLUTE)
  226. ")
  227. if("${absInstallDir}" MATCHES "^(/usr)?/lib(64)?/.+")
  228. # Handle "/usr move" symlinks created by some Linux distros.
  229. string(APPEND PACKAGE_INIT "
  230. # Use original install prefix when loaded through a \"/usr move\"
  231. # cross-prefix symbolic link such as /lib -> /usr/lib.
  232. get_filename_component(_realCurr \"\${CMAKE_CURRENT_LIST_DIR}\" REALPATH)
  233. get_filename_component(_realOrig \"${absInstallDir}\" REALPATH)
  234. if(_realCurr STREQUAL _realOrig)
  235. set(PACKAGE_PREFIX_DIR \"${installPrefix}\")
  236. endif()
  237. unset(_realOrig)
  238. unset(_realCurr)
  239. ")
  240. endif()
  241. if(NOT CCF_NO_SET_AND_CHECK_MACRO)
  242. string(APPEND PACKAGE_INIT "
  243. macro(set_and_check _var _file)
  244. set(\${_var} \"\${_file}\")
  245. if(NOT EXISTS \"\${_file}\")
  246. message(FATAL_ERROR \"File or directory \${_file} referenced by variable \${_var} does not exist !\")
  247. endif()
  248. endmacro()
  249. ")
  250. endif()
  251. if(NOT CCF_NO_CHECK_REQUIRED_COMPONENTS_MACRO)
  252. string(APPEND PACKAGE_INIT "
  253. macro(check_required_components _NAME)
  254. foreach(comp \${\${_NAME}_FIND_COMPONENTS})
  255. if(NOT \${_NAME}_\${comp}_FOUND)
  256. if(\${_NAME}_FIND_REQUIRED_\${comp})
  257. set(\${_NAME}_FOUND FALSE)
  258. endif()
  259. endif()
  260. endforeach()
  261. endmacro()
  262. ")
  263. endif()
  264. string(APPEND PACKAGE_INIT "
  265. ####################################################################################")
  266. configure_file("${_inputFile}" "${_outputFile}" @ONLY)
  267. endfunction()