index.rst 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. Using Dependencies Guide
  2. ************************
  3. .. only:: html
  4. .. contents::
  5. Introduction
  6. ============
  7. Projects will frequently depend on other projects, assets, and artifacts.
  8. CMake provides a number of ways to incorporate such things into the build.
  9. Projects and users have the flexibility to choose between methods that
  10. best suit their needs.
  11. The primary methods of bringing dependencies into the build are the
  12. :command:`find_package` command and the :module:`FetchContent` module.
  13. The :module:`FindPkgConfig` module is also sometimes used, although it
  14. lacks some of the integration of the other two and is not discussed any
  15. further in this guide.
  16. Dependencies can also be made available by a custom
  17. :ref:`dependency provider <dependency_providers>`.
  18. This might be a third party package manager, or it might be custom code
  19. implemented by the developer. Dependency providers co-operate with the
  20. primary methods mentioned above to extend their flexibility.
  21. .. _prebuilt_find_package:
  22. Using Pre-built Packages With ``find_package()``
  23. ================================================
  24. A package needed by the project may already be built and available at some
  25. location on the user's system. That package might have also been built by
  26. CMake, or it could have used a different build system entirely. It might
  27. even just be a collection of files that didn't need to be built at all.
  28. CMake provides the :command:`find_package` command for these scenarios.
  29. It searches well-known locations, along with additional hints and paths
  30. provided by the project or user. It also supports package components and
  31. packages being optional. Result variables are provided to allow the project
  32. to customize its own behavior according to whether the package or specific
  33. components were found.
  34. In most cases, projects should generally use the :ref:`basic signature`.
  35. Most of the time, this will involve just the package name, maybe a version
  36. constraint, and the ``REQUIRED`` keyword if the dependency is not optional.
  37. A set of package components may also be specified.
  38. .. code-block:: cmake
  39. :caption: Examples of ``find_package()`` basic signature
  40. find_package(Catch2)
  41. find_package(GTest REQUIRED)
  42. find_package(Boost 1.79 COMPONENTS date_time)
  43. The :command:`find_package` command supports two main methods for carrying
  44. out the search:
  45. **Config mode**
  46. With this method, the command looks for files that are typically provided
  47. by the package itself. This is the more reliable method of the two, since
  48. the package details should always be in sync with the package.
  49. **Module mode**
  50. Not all packages are CMake-aware. Many don't provide the files needed to
  51. support config mode. For such cases, a Find module file can be provided
  52. separately, either by the project or by CMake. A Find module is typically
  53. a heuristic implementation which knows what the package normally provides
  54. and how to present that package to the project. Since Find modules are
  55. usually distributed separately from the package, they are not as reliable.
  56. They are typically maintained separately, and they are likely to follow
  57. different release schedules, so they can easily become out-of-date.
  58. Depending on the arguments used, :command:`find_package` may use one or both
  59. of the above methods. By restricting the options to just the basic signature,
  60. both config mode and module mode can be used to satisfy the dependency.
  61. The presence of other options may restrict the call to using only one of the
  62. two methods, potentially reducing the command's ability to find the dependency.
  63. See the :command:`find_package` documentation for full details about this
  64. complex topic.
  65. For both search methods, the user can also set cache variables on the
  66. :manual:`cmake(1)` command line or in the :manual:`ccmake(1)` or
  67. :manual:`cmake-gui(1)` UI tools to influence and override where to find
  68. packages. See the :ref:`User Interaction Guide <Setting Build Variables>`
  69. for more on how to set cache variables.
  70. .. _Libraries providing Config-file packages:
  71. Config-file packages
  72. --------------------
  73. The preferred way for a third party to provide executables, libraries,
  74. headers, and other files for use with CMake is to provide
  75. :ref:`config files <Config File Packages>`. These are text files shipped
  76. with the package, which define CMake targets, variables, commands, and so on.
  77. The config file is an ordinary CMake script, which is read in by the
  78. :command:`find_package` command.
  79. The config files can usually be found in a directory whose name matches the
  80. pattern ``lib/cmake/<PackageName>``, although they may be in other locations
  81. instead (see :ref:`search procedure`). The ``<PackageName>`` is usually the
  82. first argument to the :command:`find_package` command, and it may even be the
  83. only argument. Alternative names can also be specified with the ``NAMES``
  84. option:
  85. .. code-block:: cmake
  86. :caption: Providing alternative names when finding a package
  87. find_package(SomeThing
  88. NAMES
  89. SameThingOtherName # Another name for the package
  90. SomeThing # Also still look for its canonical name
  91. )
  92. The config file must be named either ``<PackageName>Config.cmake`` or
  93. ``<LowercasePackageName>-config.cmake`` (the former is used for the remainder
  94. of this guide, but both are supported). This file is the entry point
  95. to the package for CMake. A separate optional file named
  96. ``<PackageName>ConfigVersion.cmake`` or
  97. ``<LowercasePackageName>-config-version.cmake`` may also exist in the same
  98. directory. This file is used by CMake to determine whether the version of
  99. the package satisfies any version constraint included in the call to
  100. :command:`find_package`. It is optional to specify a version when calling
  101. :command:`find_package`, even if a ``<PackageName>ConfigVersion.cmake``
  102. file is present.
  103. If the ``<PackageName>Config.cmake`` file is found and any version constraint
  104. is satisfied, the :command:`find_package` command considers the package to be
  105. found, and the entire package is assumed to be complete as designed.
  106. There may be additional files providing CMake commands or
  107. :ref:`imported targets` for you to use. CMake does not enforce any naming
  108. convention for these files. They are related to the primary
  109. ``<PackageName>Config.cmake`` file by use of the CMake :command:`include`
  110. command. The ``<PackageName>Config.cmake`` file would typically include
  111. these for you, so they won't usually require any additional step other than
  112. the call to :command:`find_package`.
  113. If the location of the package is in a
  114. :ref:`directory known to CMake <search procedure>`, the
  115. :command:`find_package` call should succeed. The directories known to CMake
  116. are platform-specific. For example, packages installed on Linux with a
  117. standard system package manager will be found in the ``/usr`` prefix
  118. automatically. Packages installed in ``Program Files`` on Windows will
  119. similarly be found automatically.
  120. Packages will not be found automatically without help if they are in
  121. locations not known to CMake, such as ``/opt/mylib`` or ``$HOME/dev/prefix``.
  122. This is a normal situation, and CMake provides several ways for users to
  123. specify where to find such libraries.
  124. The :variable:`CMAKE_PREFIX_PATH` variable may be
  125. :ref:`set when invoking CMake <Setting Build Variables>`.
  126. It is treated as a list of base paths in which to search for
  127. :ref:`config files <Config File Packages>`. A package installed in
  128. ``/opt/somepackage`` will typically install config files such as
  129. ``/opt/somepackage/lib/cmake/somePackage/SomePackageConfig.cmake``.
  130. In that case, ``/opt/somepackage`` should be added to
  131. :variable:`CMAKE_PREFIX_PATH`.
  132. The environment variable ``CMAKE_PREFIX_PATH`` may also be populated with
  133. prefixes to search for packages. Like the ``PATH`` environment variable,
  134. this is a list, but it needs to use the platform-specific environment variable
  135. list item separator (``:`` on Unix and ``;`` on Windows).
  136. The :variable:`CMAKE_PREFIX_PATH` variable provides convenience in cases
  137. where multiple prefixes need to be specified, or when multiple packages
  138. are available under the same prefix. Paths to packages may also be
  139. specified by setting variables matching ``<PackageName>_DIR``, such as
  140. ``SomePackage_DIR``. Note that this is not a prefix, but should be a full
  141. path to a directory containing a config-style package file, such as
  142. ``/opt/somepackage/lib/cmake/SomePackage`` in the above example.
  143. See the :command:`find_package` documentation for other CMake variables and
  144. environment variables that can affect the search.
  145. .. _Libraries not Providing Config-file Packages:
  146. Find Module Files
  147. -----------------
  148. Packages which do not provide config files can still be found with the
  149. :command:`find_package` command, if a ``FindSomePackage.cmake`` file is
  150. available. These Find module files are different to config files in that:
  151. #. Find module files should not be provided by the package itself.
  152. #. The availability of a ``Find<PackageName>.cmake`` file does not indicate
  153. the availability of the package, or any particular part of the package.
  154. #. CMake does not search the locations specified in the
  155. :variable:`CMAKE_PREFIX_PATH` variable for ``Find<PackageName>.cmake``
  156. files. Instead, CMake searches for such files in the locations given
  157. by the :variable:`CMAKE_MODULE_PATH` variable. It is common for users to
  158. set the :variable:`CMAKE_MODULE_PATH` when running CMake, and it is common
  159. for CMake projects to append to :variable:`CMAKE_MODULE_PATH` to allow use
  160. of local Find module files.
  161. #. CMake ships ``Find<PackageName>.cmake`` files for some
  162. :manual:`third party packages <cmake-modules(7)>`. These files are a
  163. maintenance burden for CMake, and it is not unusual for these to fall
  164. behind the latest releases of the packages they are associated with.
  165. In general, new Find modules are not added to CMake any more. Projects
  166. should encourage the upstream packages to provide a config file where
  167. possible. If that is unsuccessful, the project should provide its own
  168. Find module for the package.
  169. See :ref:`Find Modules` for a detailed discussion of how to write a
  170. Find module file.
  171. .. _Imported Targets from Packages:
  172. Imported Targets
  173. ----------------
  174. Both config files and Find module files can define :ref:`Imported targets`.
  175. These will typically have names of the form ``SomePrefix::ThingName``.
  176. Where these are available, the project should prefer to use them instead of
  177. any CMake variables that may also be provided. Such targets typically carry
  178. usage requirements and apply things like header search paths, compiler
  179. definitions, etc. automatically to other targets that link to them (e.g. using
  180. :command:`target_link_libraries`). This is both more robust and more
  181. convenient than trying to apply the same things manually using variables.
  182. Check the documentation for the package or Find module to see what imported
  183. targets it defines, if any.
  184. Imported targets should also encapsulate any configuration-specific paths.
  185. This includes the location of binaries (libraries, executables), compiler
  186. flags, and any other configuration-dependent quantities. Find modules may
  187. be less reliable in providing these details than config files.
  188. A complete example which finds a third party package and uses a library
  189. from it might look like the following:
  190. .. code-block:: cmake
  191. cmake_minimum_required(VERSION 3.10)
  192. project(MyExeProject VERSION 1.0.0)
  193. # Make project-provided Find modules available
  194. list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
  195. find_package(SomePackage REQUIRED)
  196. add_executable(MyExe main.cpp)
  197. target_link_libraries(MyExe PRIVATE SomePrefix::LibName)
  198. Note that the above call to :command:`find_package` could be resolved by
  199. a config file or a Find module. It uses only the basic arguments supported
  200. by the :ref:`basic signature`. A ``FindSomePackage.cmake`` file in the
  201. ``${CMAKE_CURRENT_SOURCE_DIR}/cmake`` directory would allow the
  202. :command:`find_package` command to succeed using module mode, for example.
  203. If no such module file is present, the system would be searched for a config
  204. file.
  205. Downloading And Building From Source With ``FetchContent``
  206. ==========================================================
  207. Dependencies do not necessarily have to be pre-built in order to use them
  208. with CMake. They can be built from sources as part of the main project.
  209. The :module:`FetchContent` module provides functionality to download
  210. content (typically sources, but can be anything) and add it to the main
  211. project if the dependency also uses CMake. The dependency's sources will
  212. be built along with the rest of the project, just as though the sources were
  213. part of the project's own sources.
  214. The general pattern is that the project should first declare all the
  215. dependencies it wants to use, then ask for them to be made available.
  216. The following demonstrates the principle (see :ref:`fetch-content-examples`
  217. for more):
  218. .. code-block:: cmake
  219. include(FetchContent)
  220. FetchContent_Declare(
  221. googletest
  222. GIT_REPOSITORY https://github.com/google/googletest.git
  223. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  224. )
  225. FetchContent_Declare(
  226. Catch2
  227. GIT_REPOSITORY https://github.com/catchorg/Catch2.git
  228. GIT_TAG 605a34765aa5d5ecbf476b4598a862ada971b0cc # v3.0.1
  229. )
  230. FetchContent_MakeAvailable(googletest Catch2)
  231. Various download methods are supported, including downloading and extracting
  232. archives from a URL (a range of archive formats are supported), and a number
  233. of repository formats including Git, Subversion, and Mercurial.
  234. Custom download, update, and patch commands can also be used to support
  235. arbitrary use cases.
  236. When a dependency is added to the project with :module:`FetchContent`, the
  237. project links to the dependency's targets just like any other target from the
  238. project. If the dependency provides namespaced targets of the form
  239. ``SomePrefix::ThingName``, the project should link to those rather than to
  240. any non-namespaced targets. See the next section for why this is recommended.
  241. Not all dependencies can be brought into the project this way. Some
  242. dependencies define targets whose names clash with other targets from the
  243. project or other dependencies. Concrete executable and library targets
  244. created by :command:`add_executable` and :command:`add_library` are global,
  245. so each one must be unique across the whole build. If a dependency would
  246. add a clashing target name, it cannot be brought directly into the build
  247. with this method.
  248. ``FetchContent`` And ``find_package()`` Integration
  249. ===================================================
  250. .. versionadded:: 3.24
  251. Some dependencies support being added by either :command:`find_package` or
  252. :module:`FetchContent`. Such dependencies must ensure they define the same
  253. namespaced targets in both installed and built-from-source scenarios.
  254. A consuming project then links to those namespaced targets and can handle
  255. both scenarios transparently, as long as the project does not use anything
  256. else that isn't provided by both methods.
  257. The project can indicate it is happy to accept a dependency by either method
  258. using the ``FIND_PACKAGE_ARGS`` option to :command:`FetchContent_Declare`.
  259. This allows :command:`FetchContent_MakeAvailable` to try satisfying the
  260. dependency with a call to :command:`find_package` first, using the arguments
  261. after the ``FIND_PACKAGE_ARGS`` keyword, if any. If that doesn't find the
  262. dependency, it is built from source as described previously instead.
  263. .. code-block:: cmake
  264. include(FetchContent)
  265. FetchContent_Declare(
  266. googletest
  267. GIT_REPOSITORY https://github.com/google/googletest.git
  268. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  269. FIND_PACKAGE_ARGS NAMES GTest
  270. )
  271. FetchContent_MakeAvailable(googletest)
  272. add_executable(ThingUnitTest thing_ut.cpp)
  273. target_link_libraries(ThingUnitTest GTest::gtest_main)
  274. The above example calls
  275. :command:`find_package(googletest NAMES GTest) <find_package>` first.
  276. CMake provides a :module:`FindGTest` module, so if that finds a GTest package
  277. installed somewhere, it will make it available, and the dependency will not be
  278. built from source. If no GTest package is found, it *will* be built from
  279. source. In either case, the ``GTest::gtest_main`` target is expected to be
  280. defined, so we link our unit test executable to that target.
  281. High-level control is also available through the
  282. :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` variable. This can be set to
  283. ``NEVER`` to disable all redirection to :command:`find_package`. It can be
  284. set to ``ALWAYS`` to try :command:`find_package` even if ``FIND_PACKAGE_ARGS``
  285. was not specified (this should be used with caution).
  286. The project might also decide that a particular dependency must be built from
  287. source. This might be needed if a patched or unreleased version of the
  288. dependency is required, or to satisfy some policy that requires all
  289. dependencies to be built from source. The project can enforce this by adding
  290. the ``OVERRIDE_FIND_PACKAGE`` keyword to :command:`FetchContent_Declare`.
  291. A call to :command:`find_package` for that dependency will then be redirected
  292. to :command:`FetchContent_MakeAvailable` instead.
  293. .. code-block:: cmake
  294. include(FetchContent)
  295. FetchContent_Declare(
  296. Catch2
  297. URL https://intranet.mycomp.com/vendored/Catch2_2.13.4_patched.tgz
  298. URL_HASH MD5=abc123...
  299. OVERRIDE_FIND_PACKAGE
  300. )
  301. # The following is automatically redirected to FetchContent_MakeAvailable(Catch2)
  302. find_package(Catch2)
  303. For more advanced use cases, see the
  304. :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` variable.
  305. .. _dependency_providers_overview:
  306. Dependency Providers
  307. ====================
  308. .. versionadded:: 3.24
  309. The preceding section discussed techniques that projects can use to specify
  310. their dependencies. Ideally, the project shouldn't really care where a
  311. dependency comes from, as long as it provides the things it expects (often
  312. just some imported targets). The project says what it needs and may also
  313. specify where to get it from, in the absence of any other details, so that it
  314. can still be built out-of-the-box.
  315. The developer, on the other hand, may be much more interested in controlling
  316. *how* a dependency is provided to the project. You might want to use a
  317. particular version of a package that you built yourself. You might want
  318. to use a third party package manager. You might want to redirect some
  319. requests to a different URL on a system you control for security or
  320. performance reasons. CMake supports these sort of scenarios through
  321. :ref:`dependency_providers`.
  322. A dependency provider can be set to intercept :command:`find_package` and
  323. :command:`FetchContent_MakeAvailable` calls. The provider is given an
  324. opportunity to satisfy such requests before falling back to the built-in
  325. implementation if the provider doesn't fulfill it.
  326. Only one dependency provider can be set, and it can only be set at a very
  327. specific point early in the CMake run.
  328. The :variable:`CMAKE_PROJECT_TOP_LEVEL_INCLUDES` variable lists CMake files
  329. that will be read while processing the first :command:`project()` call (and
  330. only that call). This is the only time a dependency provider may be set.
  331. At most, one single provider is expected to be used throughout the whole
  332. project.
  333. For some scenarios, the user wouldn't need to know the details of how the
  334. dependency provider is set. A third party may provide a file that can be
  335. added to :variable:`CMAKE_PROJECT_TOP_LEVEL_INCLUDES`, which will set up
  336. the dependency provider on the user's behalf. This is the recommended
  337. approach for package managers. The developer can use such a file like so::
  338. cmake -DCMAKE_PROJECT_TOP_LEVEL_INCLUDES=/path/to/package_manager/setup.cmake ...
  339. For details on how to implement your own custom dependency provider, see the
  340. :command:`cmake_language(SET_DEPENDENCY_PROVIDER)` command.