FetchContent.cmake 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143
  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. FetchContent
  5. ------------------
  6. .. versionadded:: 3.11
  7. .. only:: html
  8. .. contents::
  9. .. note:: The :guide:`Using Dependencies Guide` provides a high-level
  10. introduction to this general topic. It provides a broader overview of
  11. where the ``FetchContent`` module fits into the bigger picture,
  12. including its relationship to the :command:`find_package` command.
  13. The guide is recommended pre-reading before moving on to the details below.
  14. Overview
  15. ^^^^^^^^
  16. This module enables populating content at configure time via any method
  17. supported by the :module:`ExternalProject` module. Whereas
  18. :command:`ExternalProject_Add` downloads at build time, the
  19. ``FetchContent`` module makes content available immediately, allowing the
  20. configure step to use the content in commands like :command:`add_subdirectory`,
  21. :command:`include` or :command:`file` operations.
  22. Content population details should be defined separately from the command that
  23. performs the actual population. This separation ensures that all the
  24. dependency details are defined before anything might try to use them to
  25. populate content. This is particularly important in more complex project
  26. hierarchies where dependencies may be shared between multiple projects.
  27. The following shows a typical example of declaring content details for some
  28. dependencies and then ensuring they are populated with a separate call:
  29. .. code-block:: cmake
  30. FetchContent_Declare(
  31. googletest
  32. GIT_REPOSITORY https://github.com/google/googletest.git
  33. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  34. )
  35. FetchContent_Declare(
  36. myCompanyIcons
  37. URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
  38. URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
  39. )
  40. FetchContent_MakeAvailable(googletest myCompanyIcons)
  41. The :command:`FetchContent_MakeAvailable` command ensures the named
  42. dependencies have been populated, either by an earlier call or by populating
  43. them itself. When performing the population, it will also add them to the
  44. main build, if possible, so that the main build can use the populated
  45. projects' targets, etc. See the command's documentation for how these steps
  46. are performed.
  47. When using a hierarchical project arrangement, projects at higher levels in
  48. the hierarchy are able to override the declared details of content specified
  49. anywhere lower in the project hierarchy. The first details to be declared
  50. for a given dependency take precedence, regardless of where in the project
  51. hierarchy that occurs. Similarly, the first call that tries to populate a
  52. dependency "wins", with subsequent populations reusing the result of the
  53. first instead of repeating the population again.
  54. See the :ref:`Examples <fetch-content-examples>` which demonstrate
  55. this scenario.
  56. In some cases, the main project may need to have more precise control over
  57. the population, or it may be required to explicitly define the population
  58. steps in a way that cannot be captured by the declared details alone.
  59. For such situations, the lower level :command:`FetchContent_GetProperties` and
  60. :command:`FetchContent_Populate` commands can be used. These lack the richer
  61. features provided by :command:`FetchContent_MakeAvailable` though, so their
  62. direct use should be considered a last resort. The typical pattern of such
  63. custom steps looks like this:
  64. .. code-block:: cmake
  65. # NOTE: Where possible, prefer to use FetchContent_MakeAvailable()
  66. # instead of custom logic like this
  67. # Check if population has already been performed
  68. FetchContent_GetProperties(depname)
  69. if(NOT depname_POPULATED)
  70. # Fetch the content using previously declared details
  71. FetchContent_Populate(depname)
  72. # Set custom variables, policies, etc.
  73. # ...
  74. # Bring the populated content into the build
  75. add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
  76. endif()
  77. The ``FetchContent`` module also supports defining and populating
  78. content in a single call, with no check for whether the content has been
  79. populated elsewhere already. This should not be done in projects, but may
  80. be appropriate for populating content in CMake's script mode.
  81. See :command:`FetchContent_Populate` for details.
  82. Commands
  83. ^^^^^^^^
  84. .. command:: FetchContent_Declare
  85. .. code-block:: cmake
  86. FetchContent_Declare(
  87. <name>
  88. <contentOptions>...
  89. [EXCLUDE_FROM_ALL]
  90. [SYSTEM]
  91. [OVERRIDE_FIND_PACKAGE |
  92. FIND_PACKAGE_ARGS args...]
  93. )
  94. The ``FetchContent_Declare()`` function records the options that describe
  95. how to populate the specified content. If such details have already
  96. been recorded earlier in this project (regardless of where in the project
  97. hierarchy), this and all later calls for the same content ``<name>`` are
  98. ignored. This "first to record, wins" approach is what allows hierarchical
  99. projects to have parent projects override content details of child projects.
  100. The content ``<name>`` can be any string without spaces, but good practice
  101. would be to use only letters, numbers and underscores. The name will be
  102. treated case-insensitively and it should be obvious for the content it
  103. represents, often being the name of the child project or the value given
  104. to its top level :command:`project` command (if it is a CMake project).
  105. For well-known public projects, the name should generally be the official
  106. name of the project. Choosing an unusual name makes it unlikely that other
  107. projects needing that same content will use the same name, leading to
  108. the content being populated multiple times.
  109. The ``<contentOptions>`` can be any of the download, update or patch options
  110. that the :command:`ExternalProject_Add` command understands. The configure,
  111. build, install and test steps are explicitly disabled and therefore options
  112. related to them will be ignored. The ``SOURCE_SUBDIR`` option is an
  113. exception, see :command:`FetchContent_MakeAvailable` for details on how that
  114. affects behavior.
  115. In most cases, ``<contentOptions>`` will just be a couple of options defining
  116. the download method and method-specific details like a commit tag or archive
  117. hash. For example:
  118. .. code-block:: cmake
  119. FetchContent_Declare(
  120. googletest
  121. GIT_REPOSITORY https://github.com/google/googletest.git
  122. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  123. )
  124. FetchContent_Declare(
  125. myCompanyIcons
  126. URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
  127. URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
  128. )
  129. FetchContent_Declare(
  130. myCompanyCertificates
  131. SVN_REPOSITORY svn+ssh://svn.mycompany.com/srv/svn/trunk/certs
  132. SVN_REVISION -r12345
  133. )
  134. Where contents are being fetched from a remote location and you do not
  135. control that server, it is advisable to use a hash for ``GIT_TAG`` rather
  136. than a branch or tag name. A commit hash is more secure and helps to
  137. confirm that the downloaded contents are what you expected.
  138. .. versionchanged:: 3.14
  139. Commands for the download, update or patch steps can access the terminal.
  140. This may be needed for things like password prompts or real-time display
  141. of command progress.
  142. .. versionadded:: 3.22
  143. The :variable:`CMAKE_TLS_VERIFY`, :variable:`CMAKE_TLS_CAINFO`,
  144. :variable:`CMAKE_NETRC` and :variable:`CMAKE_NETRC_FILE` variables now
  145. provide the defaults for their corresponding content options, just like
  146. they do for :command:`ExternalProject_Add`. Previously, these variables
  147. were ignored by the ``FetchContent`` module.
  148. .. versionadded:: 3.24
  149. ``FIND_PACKAGE_ARGS``
  150. This option is for scenarios where the
  151. :command:`FetchContent_MakeAvailable` command may first try a call to
  152. :command:`find_package` to satisfy the dependency for ``<name>``.
  153. By default, such a call would be simply ``find_package(<name>)``, but
  154. ``FIND_PACKAGE_ARGS`` can be used to provide additional arguments to be
  155. appended after the ``<name>``. ``FIND_PACKAGE_ARGS`` can also be given
  156. with nothing after it, which indicates that :command:`find_package` can
  157. still be called if :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` is
  158. set to ``OPT_IN`` or is not set.
  159. It would not normally be appropriate to specify ``REQUIRED`` as one of
  160. the additional arguments after ``FIND_PACKAGE_ARGS``. Doing so would
  161. mean the :command:`find_package` call must succeed, so none of the other
  162. details specified in the ``FetchContent_Declare()`` call would get a
  163. chance to be used as a fall-back.
  164. Everything after the ``FIND_PACKAGE_ARGS`` keyword is appended to the
  165. :command:`find_package` call, so all other ``<contentOptions>`` must
  166. come before the ``FIND_PACKAGE_ARGS`` keyword. If the
  167. :variable:`CMAKE_FIND_PACKAGE_TARGETS_GLOBAL` variable is set to true
  168. at the time ``FetchContent_Declare()`` is called, a ``GLOBAL`` keyword
  169. will be appended to the :command:`find_package` arguments if it was
  170. not already specified. It will also be appended if
  171. ``FIND_PACKAGE_ARGS`` was not given, but
  172. :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` was set to ``ALWAYS``.
  173. ``OVERRIDE_FIND_PACKAGE`` cannot be used when ``FIND_PACKAGE_ARGS`` is
  174. given.
  175. :ref:`dependency_providers` discusses another way that
  176. :command:`FetchContent_MakeAvailable` calls can be redirected.
  177. ``FIND_PACKAGE_ARGS`` is intended for project control, whereas
  178. dependency providers allow users to override project behavior.
  179. ``OVERRIDE_FIND_PACKAGE``
  180. When a ``FetchContent_Declare(<name> ...)`` call includes this option,
  181. subsequent calls to ``find_package(<name> ...)`` will ensure that
  182. ``FetchContent_MakeAvailable(<name>)`` has been called, then use the
  183. config package files in the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR`
  184. directory (which are usually created by ``FetchContent_MakeAvailable()``).
  185. This effectively makes :command:`FetchContent_MakeAvailable` override
  186. :command:`find_package` for the named dependency, allowing the former to
  187. satisfy the package requirements of the latter. ``FIND_PACKAGE_ARGS``
  188. cannot be used when ``OVERRIDE_FIND_PACKAGE`` is given.
  189. If a :ref:`dependency provider <dependency_providers>` has been set
  190. and the project calls :command:`find_package` for the ``<name>``
  191. dependency, ``OVERRIDE_FIND_PACKAGE`` will not prevent the provider
  192. from seeing that call. Dependency providers always have the opportunity
  193. to intercept any direct call to :command:`find_package`, except if that
  194. call contains the ``BYPASS_PROVIDER`` option.
  195. .. versionadded:: 3.25
  196. ``SYSTEM``
  197. If the ``SYSTEM`` argument is provided, the :prop_dir:`SYSTEM` directory
  198. property of a subdirectory added by
  199. :command:`FetchContent_MakeAvailable` will be set to true. This will
  200. affect non-imported targets created as part of that command.
  201. See the :prop_tgt:`SYSTEM` target property documentation for a more
  202. detailed discussion of the effects.
  203. .. versionadded:: 3.28
  204. ``EXCLUDE_FROM_ALL``
  205. If the ``EXCLUDE_FROM_ALL`` argument is provided, then targets in the
  206. subdirectory added by :command:`FetchContent_MakeAvailable` will not be
  207. included in the ``ALL`` target by default, and may be excluded from IDE
  208. project files. See the :command:`add_subdirectory` ``EXCLUDE_FROM_ALL``
  209. argument documentation for a more detailed discussion of the effects.
  210. .. command:: FetchContent_MakeAvailable
  211. .. versionadded:: 3.14
  212. .. code-block:: cmake
  213. FetchContent_MakeAvailable(<name1> [<name2>...])
  214. This command ensures that each of the named dependencies are made available
  215. to the project by the time it returns. There must have been a call to
  216. :command:`FetchContent_Declare` for each dependency, and the first such call
  217. will control how that dependency will be made available, as described below.
  218. If ``<lowercaseName>_SOURCE_DIR`` is not set:
  219. * .. versionadded:: 3.24
  220. If a :ref:`dependency provider <dependency_providers>` is set, call the
  221. provider's command with ``FETCHCONTENT_MAKEAVAILABLE_SERIAL`` as the
  222. first argument, followed by the arguments of the first call to
  223. :command:`FetchContent_Declare` for ``<name>``. If ``SOURCE_DIR`` or
  224. ``BINARY_DIR`` were not part of the original declared arguments, they
  225. will be added with their default values.
  226. If :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` was set to ``NEVER``
  227. when the details were declared, any ``FIND_PACKAGE_ARGS`` will be
  228. omitted. The ``OVERRIDE_FIND_PACKAGE`` keyword is also always omitted.
  229. If the provider fulfilled the request, ``FetchContent_MakeAvailable()``
  230. will consider that dependency handled, skip the remaining steps below
  231. and move on to the next dependency in the list.
  232. * .. versionadded:: 3.24
  233. If permitted, :command:`find_package(<name> [<args>...]) <find_package>`
  234. will be called, where ``<args>...`` may be provided by the
  235. ``FIND_PACKAGE_ARGS`` option in :command:`FetchContent_Declare`.
  236. The value of the :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` variable
  237. at the time :command:`FetchContent_Declare` was called determines whether
  238. ``FetchContent_MakeAvailable()`` can call :command:`find_package`.
  239. If the :variable:`CMAKE_FIND_PACKAGE_TARGETS_GLOBAL` variable is set to
  240. true when ``FetchContent_MakeAvailable()`` is called, it still affects
  241. any imported targets created when that in turn calls
  242. :command:`find_package`, even if that variable was false when the
  243. corresponding details were declared.
  244. If the dependency was not satisfied by a provider or a
  245. :command:`find_package` call, ``FetchContent_MakeAvailable()`` then uses
  246. the following logic to make the dependency available:
  247. * If the dependency has already been populated earlier in this run, set
  248. the ``<lowercaseName>_POPULATED``, ``<lowercaseName>_SOURCE_DIR`` and
  249. ``<lowercaseName>_BINARY_DIR`` variables in the same way as a call to
  250. :command:`FetchContent_GetProperties`, then skip the remaining steps
  251. below and move on to the next dependency in the list.
  252. * Call :command:`FetchContent_Populate` to populate the dependency using
  253. the details recorded by an earlier call to :command:`FetchContent_Declare`.
  254. Halt with a fatal error if no such details have been recorded.
  255. :variable:`FETCHCONTENT_SOURCE_DIR_<uppercaseName>` can be used to override
  256. the declared details and use content provided at the specified location
  257. instead.
  258. * .. versionadded:: 3.24
  259. Ensure the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` directory
  260. contains a ``<lowercaseName>-config.cmake`` and a
  261. ``<lowercaseName>-config-version.cmake`` file (or equivalently
  262. ``<name>Config.cmake`` and ``<name>ConfigVersion.cmake``).
  263. The directory that the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR`
  264. variable points to is cleared at the start of every CMake run.
  265. If no config file exists when :command:`FetchContent_Populate` returns,
  266. a minimal one will be written which :command:`includes <include>` any
  267. ``<lowercaseName>-extra.cmake`` or ``<name>Extra.cmake`` file with the
  268. ``OPTIONAL`` flag (so the files can be missing and won't generate a
  269. warning). Similarly, if no config version file exists, a very simple
  270. one will be written which sets ``PACKAGE_VERSION_COMPATIBLE`` and
  271. ``PACKAGE_VERSION_EXACT`` to true. This ensures all future calls to
  272. :command:`find_package()` for the dependency will use the redirected
  273. config file, regardless of any version requirements.
  274. CMake cannot automatically determine an arbitrary dependency's version,
  275. so it cannot set ``PACKAGE_VERSION``.
  276. When a dependency is pulled in via :command:`add_subdirectory` in the
  277. next step, it may choose to overwrite the generated config version file
  278. in :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` with one that also sets
  279. ``PACKAGE_VERSION``.
  280. The dependency may also write a ``<lowercaseName>-extra.cmake`` or
  281. ``<name>Extra.cmake`` file to perform custom processing or define any
  282. variables that their normal (installed) package config file would
  283. otherwise usually define (many projects don't do any custom processing
  284. or set any variables and therefore have no need to do this).
  285. If required, the main project can write these files instead if the
  286. dependency project doesn't do so. This allows the main project to
  287. add missing details from older dependencies that haven't or can't be
  288. updated to support this functionality.
  289. See `Integrating With find_package()`_ for examples.
  290. * If the top directory of the populated content contains a ``CMakeLists.txt``
  291. file, call :command:`add_subdirectory` to add it to the main build.
  292. It is not an error for there to be no ``CMakeLists.txt`` file, which
  293. allows the command to be used for dependencies that make downloaded
  294. content available at a known location, but which do not need or support
  295. being added directly to the build.
  296. .. versionadded:: 3.18
  297. The ``SOURCE_SUBDIR`` option can be given in the declared details to
  298. look somewhere below the top directory instead (i.e. the same way that
  299. ``SOURCE_SUBDIR`` is used by the :command:`ExternalProject_Add`
  300. command). The path provided with ``SOURCE_SUBDIR`` must be relative
  301. and will be treated as relative to the top directory. It can also
  302. point to a directory that does not contain a ``CMakeLists.txt`` file
  303. or even to a directory that doesn't exist. This can be used to avoid
  304. adding a project that contains a ``CMakeLists.txt`` file in its top
  305. directory.
  306. .. versionadded:: 3.25
  307. If the ``SYSTEM`` keyword was included in the call to
  308. :command:`FetchContent_Declare`, the ``SYSTEM`` keyword will be
  309. added to the :command:`add_subdirectory` command as well.
  310. .. versionadded:: 3.28
  311. If the ``EXCLUDE_FROM_ALL`` keyword was included in the call to
  312. :command:`FetchContent_Declare`, the ``EXCLUDE_FROM_ALL`` keyword will
  313. be added to the :command:`add_subdirectory` command as well.
  314. .. versionadded:: 3.29
  315. :variable:`CMAKE_EXPORT_FIND_PACKAGE_NAME` is set to the dependency name
  316. before calling :command:`add_subdirectory`.
  317. Projects should aim to declare the details of all dependencies they might
  318. use before they call ``FetchContent_MakeAvailable()`` for any of them.
  319. This ensures that if any of the dependencies are also sub-dependencies of
  320. one or more of the others, the main project still controls the details
  321. that will be used (because it will declare them first before the
  322. dependencies get a chance to). In the following code samples, assume that
  323. the ``uses_other`` dependency also uses ``FetchContent`` to add the ``other``
  324. dependency internally:
  325. .. code-block:: cmake
  326. # WRONG: Should declare all details first
  327. FetchContent_Declare(uses_other ...)
  328. FetchContent_MakeAvailable(uses_other)
  329. FetchContent_Declare(other ...) # Will be ignored, uses_other beat us to it
  330. FetchContent_MakeAvailable(other) # Would use details declared by uses_other
  331. .. code-block:: cmake
  332. # CORRECT: All details declared first, so they will take priority
  333. FetchContent_Declare(uses_other ...)
  334. FetchContent_Declare(other ...)
  335. FetchContent_MakeAvailable(uses_other other)
  336. Note that :variable:`CMAKE_VERIFY_INTERFACE_HEADER_SETS` is explicitly set
  337. to false upon entry to ``FetchContent_MakeAvailable()``, and is restored to
  338. its original value before the command returns. Developers typically only
  339. want to verify header sets from the main project, not those from any
  340. dependencies. This local manipulation of the
  341. :variable:`CMAKE_VERIFY_INTERFACE_HEADER_SETS` variable provides that
  342. intuitive behavior. You can use variables like
  343. :variable:`CMAKE_PROJECT_INCLUDE` or
  344. :variable:`CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE` to turn verification back
  345. on for all or some dependencies. You can also set the
  346. :prop_tgt:`VERIFY_INTERFACE_HEADER_SETS` property of individual targets.
  347. .. command:: FetchContent_Populate
  348. .. note::
  349. Where possible, prefer to use :command:`FetchContent_MakeAvailable`
  350. instead of implementing population manually with this command.
  351. .. code-block:: cmake
  352. FetchContent_Populate(<name>)
  353. In most cases, the only argument given to ``FetchContent_Populate()`` is the
  354. ``<name>``. When used this way, the command assumes the content details have
  355. been recorded by an earlier call to :command:`FetchContent_Declare`. The
  356. details are stored in a global property, so they are unaffected by things
  357. like variable or directory scope. Therefore, it doesn't matter where in the
  358. project the details were previously declared, as long as they have been
  359. declared before the call to ``FetchContent_Populate()``. Those saved details
  360. are then used to construct a call to :command:`ExternalProject_Add` in a
  361. private sub-build to perform the content population immediately. The
  362. implementation of ``ExternalProject_Add()`` ensures that if the content has
  363. already been populated in a previous CMake run, that content will be reused
  364. rather than repopulating them again. For the common case where population
  365. involves downloading content, the cost of the download is only paid once.
  366. An internal global property records when a particular content population
  367. request has been processed. If ``FetchContent_Populate()`` is called more
  368. than once for the same content name within a configure run, the second call
  369. will halt with an error. Projects can and should check whether content
  370. population has already been processed with the
  371. :command:`FetchContent_GetProperties` command before calling
  372. ``FetchContent_Populate()``.
  373. ``FetchContent_Populate()`` will set three variables in the scope of the
  374. caller:
  375. ``<lowercaseName>_POPULATED``
  376. This will always be set to ``TRUE`` by the call.
  377. ``<lowercaseName>_SOURCE_DIR``
  378. The location where the populated content can be found upon return.
  379. ``<lowercaseName>_BINARY_DIR``
  380. A directory intended for use as a corresponding build directory.
  381. The main use case for the ``<lowercaseName>_SOURCE_DIR`` and
  382. ``<lowercaseName>_BINARY_DIR`` variables is to call
  383. :command:`add_subdirectory` immediately after population:
  384. .. code-block:: cmake
  385. FetchContent_Populate(FooBar)
  386. add_subdirectory(${foobar_SOURCE_DIR} ${foobar_BINARY_DIR})
  387. The values of the three variables can also be retrieved from anywhere in the
  388. project hierarchy using the :command:`FetchContent_GetProperties` command.
  389. The ``FetchContent_Populate()`` command also supports a syntax allowing the
  390. content details to be specified directly rather than using any saved
  391. details. This is more low-level and use of this form is generally to be
  392. avoided in favor of using saved content details as outlined above.
  393. Nevertheless, in certain situations it can be useful to invoke the content
  394. population as an isolated operation (typically as part of implementing some
  395. other higher level feature or when using CMake in script mode):
  396. .. code-block:: cmake
  397. FetchContent_Populate(
  398. <name>
  399. [QUIET]
  400. [SUBBUILD_DIR <subBuildDir>]
  401. [SOURCE_DIR <srcDir>]
  402. [BINARY_DIR <binDir>]
  403. ...
  404. )
  405. This form has a number of key differences to that where only ``<name>`` is
  406. provided:
  407. - All required population details are assumed to have been provided directly
  408. in the call to ``FetchContent_Populate()``. Any saved details for
  409. ``<name>`` are ignored.
  410. - No check is made for whether content for ``<name>`` has already been
  411. populated.
  412. - No global property is set to record that the population has occurred.
  413. - No global properties record the source or binary directories used for the
  414. populated content.
  415. - The ``FETCHCONTENT_FULLY_DISCONNECTED`` and
  416. ``FETCHCONTENT_UPDATES_DISCONNECTED`` cache variables are ignored.
  417. The ``<lowercaseName>_SOURCE_DIR`` and ``<lowercaseName>_BINARY_DIR``
  418. variables are still returned to the caller, but since these locations are
  419. not stored as global properties when this form is used, they are only
  420. available to the calling scope and below rather than the entire project
  421. hierarchy. No ``<lowercaseName>_POPULATED`` variable is set in the caller's
  422. scope with this form.
  423. The supported options for ``FetchContent_Populate()`` are the same as those
  424. for :command:`FetchContent_Declare()`. Those few options shown just
  425. above are either specific to ``FetchContent_Populate()`` or their behavior is
  426. slightly modified from how :command:`ExternalProject_Add` treats them:
  427. ``QUIET``
  428. The ``QUIET`` option can be given to hide the output associated with
  429. populating the specified content. If the population fails, the output will
  430. be shown regardless of whether this option was given or not so that the
  431. cause of the failure can be diagnosed. The global ``FETCHCONTENT_QUIET``
  432. cache variable has no effect on ``FetchContent_Populate()`` calls where the
  433. content details are provided directly.
  434. ``SUBBUILD_DIR``
  435. The ``SUBBUILD_DIR`` argument can be provided to change the location of the
  436. sub-build created to perform the population. The default value is
  437. ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-subbuild`` and it would be
  438. unusual to need to override this default. If a relative path is specified,
  439. it will be interpreted as relative to :variable:`CMAKE_CURRENT_BINARY_DIR`.
  440. This option should not be confused with the ``SOURCE_SUBDIR`` option which
  441. only affects the :command:`FetchContent_MakeAvailable` command.
  442. ``SOURCE_DIR``, ``BINARY_DIR``
  443. The ``SOURCE_DIR`` and ``BINARY_DIR`` arguments are supported by
  444. :command:`ExternalProject_Add`, but different default values are used by
  445. ``FetchContent_Populate()``. ``SOURCE_DIR`` defaults to
  446. ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-src`` and ``BINARY_DIR``
  447. defaults to ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-build``.
  448. If a relative path is specified, it will be interpreted as relative to
  449. :variable:`CMAKE_CURRENT_BINARY_DIR`.
  450. In addition to the above explicit options, any other unrecognized options are
  451. passed through unmodified to :command:`ExternalProject_Add` to perform the
  452. download, patch and update steps. The following options are explicitly
  453. prohibited (they are disabled by the ``FetchContent_Populate()`` command):
  454. - ``CONFIGURE_COMMAND``
  455. - ``BUILD_COMMAND``
  456. - ``INSTALL_COMMAND``
  457. - ``TEST_COMMAND``
  458. If using ``FetchContent_Populate()`` within CMake's script mode, be aware
  459. that the implementation sets up a sub-build which therefore requires a CMake
  460. generator and build tool to be available. If these cannot be found by
  461. default, then the :variable:`CMAKE_GENERATOR` and/or
  462. :variable:`CMAKE_MAKE_PROGRAM` variables will need to be set appropriately
  463. on the command line invoking the script.
  464. .. versionadded:: 3.18
  465. Added support for the ``DOWNLOAD_NO_EXTRACT`` option.
  466. .. command:: FetchContent_GetProperties
  467. When using saved content details, a call to
  468. :command:`FetchContent_MakeAvailable` or :command:`FetchContent_Populate`
  469. records information in global properties which can be queried at any time.
  470. This information may include the source and binary directories associated with
  471. the content and also whether or not the content population has been processed
  472. during the current configure run.
  473. .. code-block:: cmake
  474. FetchContent_GetProperties(
  475. <name>
  476. [SOURCE_DIR <srcDirVar>]
  477. [BINARY_DIR <binDirVar>]
  478. [POPULATED <doneVar>]
  479. )
  480. The ``SOURCE_DIR``, ``BINARY_DIR`` and ``POPULATED`` options can be used to
  481. specify which properties should be retrieved. Each option accepts a value
  482. which is the name of the variable in which to store that property. Most of
  483. the time though, only ``<name>`` is given, in which case the call will then
  484. set the same variables as a call to
  485. :command:`FetchContent_MakeAvailable(name) <FetchContent_MakeAvailable>` or
  486. :command:`FetchContent_Populate(name) <FetchContent_Populate>`.
  487. Note that the ``SOURCE_DIR`` and ``BINARY_DIR`` values can be empty if the
  488. call is fulfilled by a :ref:`dependency provider <dependency_providers>`.
  489. This command is rarely needed when using
  490. :command:`FetchContent_MakeAvailable`. It is more commonly used as part of
  491. implementing the following pattern with :command:`FetchContent_Populate`,
  492. which ensures that the relevant variables will always be defined regardless
  493. of whether or not the population has been performed elsewhere in the project
  494. already:
  495. .. code-block:: cmake
  496. # Check if population has already been performed
  497. FetchContent_GetProperties(depname)
  498. if(NOT depname_POPULATED)
  499. # Fetch the content using previously declared details
  500. FetchContent_Populate(depname)
  501. # Set custom variables, policies, etc.
  502. # ...
  503. # Bring the populated content into the build
  504. add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
  505. endif()
  506. .. command:: FetchContent_SetPopulated
  507. .. versionadded:: 3.24
  508. .. note::
  509. This command should only be called by
  510. :ref:`dependency providers <dependency_providers>`. Calling it in any
  511. other context is unsupported and future CMake versions may halt with a
  512. fatal error in such cases.
  513. .. code-block:: cmake
  514. FetchContent_SetPopulated(
  515. <name>
  516. [SOURCE_DIR <srcDir>]
  517. [BINARY_DIR <binDir>]
  518. )
  519. If a provider command fulfills a ``FETCHCONTENT_MAKEAVAILABLE_SERIAL``
  520. request, it must call this function before returning. The ``SOURCE_DIR``
  521. and ``BINARY_DIR`` arguments can be used to specify the values that
  522. :command:`FetchContent_GetProperties` should return for its corresponding
  523. arguments. Only provide ``SOURCE_DIR`` and ``BINARY_DIR`` if they have
  524. the same meaning as if they had been populated by the built-in
  525. :command:`FetchContent_MakeAvailable` implementation.
  526. Variables
  527. ^^^^^^^^^
  528. A number of cache variables can influence the behavior where details from a
  529. :command:`FetchContent_Declare` call are used to populate content.
  530. .. note::
  531. All of these variables are intended for the developer to customize behavior.
  532. They should not normally be set by the project.
  533. .. variable:: FETCHCONTENT_BASE_DIR
  534. In most cases, the saved details do not specify any options relating to the
  535. directories to use for the internal sub-build, final source and build areas.
  536. It is generally best to leave these decisions up to the ``FetchContent``
  537. module to handle on the project's behalf. The ``FETCHCONTENT_BASE_DIR``
  538. cache variable controls the point under which all content population
  539. directories are collected, but in most cases, developers would not need to
  540. change this. The default location is ``${CMAKE_BINARY_DIR}/_deps``, but if
  541. developers change this value, they should aim to keep the path short and
  542. just below the top level of the build tree to avoid running into path
  543. length problems on Windows.
  544. .. variable:: FETCHCONTENT_QUIET
  545. The logging output during population can be quite verbose, making the
  546. configure stage quite noisy. This cache option (``ON`` by default) hides
  547. all population output unless an error is encountered. If experiencing
  548. problems with hung downloads, temporarily switching this option off may
  549. help diagnose which content population is causing the issue.
  550. .. variable:: FETCHCONTENT_FULLY_DISCONNECTED
  551. When this option is enabled, no attempt is made to download or update
  552. any content. It is assumed that all content has already been populated in
  553. a previous run or the source directories have been pointed at existing
  554. contents the developer has provided manually (using options described
  555. further below). When the developer knows that no changes have been made to
  556. any content details, turning this option ``ON`` can significantly speed up
  557. the configure stage. It is ``OFF`` by default.
  558. .. note::
  559. The ``FETCHCONTENT_FULLY_DISCONNECTED`` variable is not an appropriate way
  560. to prevent any network access on the first run in a build directory.
  561. Doing so can break projects, lead to misleading error messages, and hide
  562. subtle population failures. This variable is specifically intended to
  563. only be turned on *after* the first time CMake has been run.
  564. If you want to prevent network access even on the first run, use a
  565. :ref:`dependency provider <dependency_providers>` and populate the
  566. dependency from local content instead.
  567. .. variable:: FETCHCONTENT_UPDATES_DISCONNECTED
  568. This is a less severe download/update control compared to
  569. :variable:`FETCHCONTENT_FULLY_DISCONNECTED`. Instead of bypassing all
  570. download and update logic, ``FETCHCONTENT_UPDATES_DISCONNECTED`` only
  571. prevents the update step from making connections to remote servers
  572. when using the git or hg download methods. Updates still occur if details
  573. about the update step change, but the update is attempted with only the
  574. information already available locally (so switching to a different tag or
  575. commit that is already fetched locally will succeed, but switching to an
  576. unknown commit hash will fail). The download step is not affected, so if
  577. content has not been downloaded previously, it will still be downloaded
  578. when this option is enabled. This can speed up the configure step, but
  579. not as much as :variable:`FETCHCONTENT_FULLY_DISCONNECTED`.
  580. ``FETCHCONTENT_UPDATES_DISCONNECTED`` is ``OFF`` by default.
  581. .. variable:: FETCHCONTENT_TRY_FIND_PACKAGE_MODE
  582. .. versionadded:: 3.24
  583. This variable modifies the details that :command:`FetchContent_Declare`
  584. records for a given dependency. While it ultimately controls the behavior
  585. of :command:`FetchContent_MakeAvailable`, it is the variable's value when
  586. :command:`FetchContent_Declare` is called that gets used. It makes no
  587. difference what the variable is set to when
  588. :command:`FetchContent_MakeAvailable` is called. Since the variable should
  589. only be set by the user and not by projects directly, it will typically have
  590. the same value throughout anyway, so this distinction is not usually
  591. noticeable.
  592. ``FETCHCONTENT_TRY_FIND_PACKAGE_MODE`` ultimately controls whether
  593. :command:`FetchContent_MakeAvailable` is allowed to call
  594. :command:`find_package` to satisfy a dependency. The variable can be set
  595. to one of the following values:
  596. ``OPT_IN``
  597. :command:`FetchContent_MakeAvailable` will only call
  598. :command:`find_package` if the :command:`FetchContent_Declare` call
  599. included a ``FIND_PACKAGE_ARGS`` keyword. This is also the default
  600. behavior if ``FETCHCONTENT_TRY_FIND_PACKAGE_MODE`` is not set.
  601. ``ALWAYS``
  602. :command:`find_package` can be called by
  603. :command:`FetchContent_MakeAvailable` regardless of whether the
  604. :command:`FetchContent_Declare` call included a ``FIND_PACKAGE_ARGS``
  605. keyword or not. If no ``FIND_PACKAGE_ARGS`` keyword was given, the
  606. behavior will be as though ``FIND_PACKAGE_ARGS`` had been provided,
  607. with no additional arguments after it.
  608. ``NEVER``
  609. :command:`FetchContent_MakeAvailable` will not call
  610. :command:`find_package`. Any ``FIND_PACKAGE_ARGS`` given to the
  611. :command:`FetchContent_Declare` call will be ignored.
  612. As a special case, if the :variable:`FETCHCONTENT_SOURCE_DIR_<uppercaseName>`
  613. variable has a non-empty value for a dependency, it is assumed that the
  614. user is overriding all other methods of making that dependency available.
  615. ``FETCHCONTENT_TRY_FIND_PACKAGE_MODE`` will have no effect on that
  616. dependency and :command:`FetchContent_MakeAvailable` will not try to call
  617. :command:`find_package` for it.
  618. In addition to the above, the following variables are also defined for each
  619. content name:
  620. .. variable:: FETCHCONTENT_SOURCE_DIR_<uppercaseName>
  621. If this is set, no download or update steps are performed for the specified
  622. content and the ``<lowercaseName>_SOURCE_DIR`` variable returned to the
  623. caller is pointed at this location. This gives developers a way to have a
  624. separate checkout of the content that they can modify freely without
  625. interference from the build. The build simply uses that existing source,
  626. but it still defines ``<lowercaseName>_BINARY_DIR`` to point inside its own
  627. build area. Developers are strongly encouraged to use this mechanism rather
  628. than editing the sources populated in the default location, as changes to
  629. sources in the default location can be lost when content population details
  630. are changed by the project.
  631. .. variable:: FETCHCONTENT_UPDATES_DISCONNECTED_<uppercaseName>
  632. This is the per-content equivalent of
  633. :variable:`FETCHCONTENT_UPDATES_DISCONNECTED`. If the global option or
  634. this option is ``ON``, then updates for the git and hg methods will not
  635. contact any remote for the named content. They will only use information
  636. already available locally. Disabling updates for individual content can
  637. be useful for content whose details rarely change, while still leaving
  638. other frequently changing content with updates enabled.
  639. .. _`fetch-content-examples`:
  640. Examples
  641. ^^^^^^^^
  642. Typical Case
  643. """"""""""""
  644. This first fairly straightforward example ensures that some popular testing
  645. frameworks are available to the main build:
  646. .. code-block:: cmake
  647. include(FetchContent)
  648. FetchContent_Declare(
  649. googletest
  650. GIT_REPOSITORY https://github.com/google/googletest.git
  651. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  652. )
  653. FetchContent_Declare(
  654. Catch2
  655. GIT_REPOSITORY https://github.com/catchorg/Catch2.git
  656. GIT_TAG 605a34765aa5d5ecbf476b4598a862ada971b0cc # v3.0.1
  657. )
  658. # After the following call, the CMake targets defined by googletest and
  659. # Catch2 will be available to the rest of the build
  660. FetchContent_MakeAvailable(googletest Catch2)
  661. .. _FetchContent-find_package-integration-examples:
  662. Integrating With find_package()
  663. """""""""""""""""""""""""""""""
  664. For the previous example, if the user wanted to try to find ``googletest``
  665. and ``Catch2`` via :command:`find_package` first before trying to download
  666. and build them from source, they could set the
  667. :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` variable to ``ALWAYS``.
  668. This would also affect any other calls to :command:`FetchContent_Declare`
  669. throughout the project, which might not be acceptable. The behavior can be
  670. enabled for just these two dependencies instead by adding ``FIND_PACKAGE_ARGS``
  671. to the declared details and leaving
  672. :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` unset, or set to ``OPT_IN``:
  673. .. code-block:: cmake
  674. include(FetchContent)
  675. FetchContent_Declare(
  676. googletest
  677. GIT_REPOSITORY https://github.com/google/googletest.git
  678. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  679. FIND_PACKAGE_ARGS NAMES GTest
  680. )
  681. FetchContent_Declare(
  682. Catch2
  683. GIT_REPOSITORY https://github.com/catchorg/Catch2.git
  684. GIT_TAG 605a34765aa5d5ecbf476b4598a862ada971b0cc # v3.0.1
  685. FIND_PACKAGE_ARGS
  686. )
  687. # This will try calling find_package() first for both dependencies
  688. FetchContent_MakeAvailable(googletest Catch2)
  689. For ``Catch2``, no additional arguments to :command:`find_package` are needed,
  690. so no additional arguments are provided after the ``FIND_PACKAGE_ARGS``
  691. keyword. For ``googletest``, its package is more commonly called ``GTest``,
  692. so arguments are added to support it being found by that name.
  693. If the user wanted to disable :command:`FetchContent_MakeAvailable` from
  694. calling :command:`find_package` for any dependency, even if it provided
  695. ``FIND_PACKAGE_ARGS`` in its declared details, they could set
  696. :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` to ``NEVER``.
  697. If the project wanted to indicate that these two dependencies should be
  698. downloaded and built from source and that :command:`find_package` calls
  699. should be redirected to use the built dependencies, the
  700. ``OVERRIDE_FIND_PACKAGE`` option should be used when declaring the content
  701. details:
  702. .. code-block:: cmake
  703. include(FetchContent)
  704. FetchContent_Declare(
  705. googletest
  706. GIT_REPOSITORY https://github.com/google/googletest.git
  707. GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
  708. OVERRIDE_FIND_PACKAGE
  709. )
  710. FetchContent_Declare(
  711. Catch2
  712. GIT_REPOSITORY https://github.com/catchorg/Catch2.git
  713. GIT_TAG 605a34765aa5d5ecbf476b4598a862ada971b0cc # v3.0.1
  714. OVERRIDE_FIND_PACKAGE
  715. )
  716. # The following will automatically forward through to FetchContent_MakeAvailable()
  717. find_package(googletest)
  718. find_package(Catch2)
  719. CMake provides a FindGTest module which defines some variables that older
  720. projects may use instead of linking to the imported targets. To support
  721. those cases, we can provide an extra file. In keeping with the
  722. "first to define, wins" philosophy of ``FetchContent``, we only write out
  723. that file if something else hasn't already done so.
  724. .. code-block:: cmake
  725. FetchContent_MakeAvailable(googletest)
  726. if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-extra.cmake AND
  727. NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletestExtra.cmake)
  728. file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-extra.cmake
  729. [=[
  730. if("${GTEST_LIBRARIES}" STREQUAL "" AND TARGET GTest::gtest)
  731. set(GTEST_LIBRARIES GTest::gtest)
  732. endif()
  733. if("${GTEST_MAIN_LIBRARIES}" STREQUAL "" AND TARGET GTest::gtest_main)
  734. set(GTEST_MAIN_LIBRARIES GTest::gtest_main)
  735. endif()
  736. if("${GTEST_BOTH_LIBRARIES}" STREQUAL "")
  737. set(GTEST_BOTH_LIBRARIES ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES})
  738. endif()
  739. ]=])
  740. endif()
  741. Projects will also likely be using ``find_package(GTest)`` rather than
  742. ``find_package(googletest)``, but it is possible to make use of the
  743. :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` area to pull in the latter as
  744. a dependency of the former. This is likely to be sufficient to satisfy
  745. a typical ``find_package(GTest)`` call.
  746. .. code-block:: cmake
  747. FetchContent_MakeAvailable(googletest)
  748. if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake AND
  749. NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfig.cmake)
  750. file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake
  751. [=[
  752. include(CMakeFindDependencyMacro)
  753. find_dependency(googletest)
  754. ]=])
  755. endif()
  756. if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config-version.cmake AND
  757. NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfigVersion.cmake)
  758. file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config-version.cmake
  759. [=[
  760. include(${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-config-version.cmake OPTIONAL)
  761. if(NOT PACKAGE_VERSION_COMPATIBLE)
  762. include(${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletestConfigVersion.cmake OPTIONAL)
  763. endif()
  764. ]=])
  765. endif()
  766. Overriding Where To Find CMakeLists.txt
  767. """""""""""""""""""""""""""""""""""""""
  768. If the sub-project's ``CMakeLists.txt`` file is not at the top level of its
  769. source tree, the ``SOURCE_SUBDIR`` option can be used to tell ``FetchContent``
  770. where to find it. The following example shows how to use that option, and
  771. it also sets a variable which is meaningful to the subproject before pulling
  772. it into the main build (set as an ``INTERNAL`` cache variable to avoid
  773. problems with policy :policy:`CMP0077`):
  774. .. code-block:: cmake
  775. include(FetchContent)
  776. FetchContent_Declare(
  777. protobuf
  778. GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git
  779. GIT_TAG ae50d9b9902526efd6c7a1907d09739f959c6297 # v3.15.0
  780. SOURCE_SUBDIR cmake
  781. )
  782. set(protobuf_BUILD_TESTS OFF CACHE INTERNAL "")
  783. FetchContent_MakeAvailable(protobuf)
  784. Complex Dependency Hierarchies
  785. """"""""""""""""""""""""""""""
  786. In more complex project hierarchies, the dependency relationships can be more
  787. complicated. Consider a hierarchy where ``projA`` is the top level project and
  788. it depends directly on projects ``projB`` and ``projC``. Both ``projB`` and
  789. ``projC`` can be built standalone and they also both depend on another project
  790. ``projD``. ``projB`` additionally depends on ``projE``. This example assumes
  791. that all five projects are available on a company git server. The
  792. ``CMakeLists.txt`` of each project might have sections like the following:
  793. .. code-block:: cmake
  794. :caption: *projA*
  795. include(FetchContent)
  796. FetchContent_Declare(
  797. projB
  798. GIT_REPOSITORY [email protected]:git/projB.git
  799. GIT_TAG 4a89dc7e24ff212a7b5167bef7ab079d
  800. )
  801. FetchContent_Declare(
  802. projC
  803. GIT_REPOSITORY [email protected]:git/projC.git
  804. GIT_TAG 4ad4016bd1d8d5412d135cf8ceea1bb9
  805. )
  806. FetchContent_Declare(
  807. projD
  808. GIT_REPOSITORY [email protected]:git/projD.git
  809. GIT_TAG origin/integrationBranch
  810. )
  811. FetchContent_Declare(
  812. projE
  813. GIT_REPOSITORY [email protected]:git/projE.git
  814. GIT_TAG v2.3-rc1
  815. )
  816. # Order is important, see notes in the discussion further below
  817. FetchContent_MakeAvailable(projD projB projC)
  818. .. code-block:: cmake
  819. :caption: *projB*
  820. include(FetchContent)
  821. FetchContent_Declare(
  822. projD
  823. GIT_REPOSITORY [email protected]:git/projD.git
  824. GIT_TAG 20b415f9034bbd2a2e8216e9a5c9e632
  825. )
  826. FetchContent_Declare(
  827. projE
  828. GIT_REPOSITORY [email protected]:git/projE.git
  829. GIT_TAG 68e20f674a48be38d60e129f600faf7d
  830. )
  831. FetchContent_MakeAvailable(projD projE)
  832. .. code-block:: cmake
  833. :caption: *projC*
  834. include(FetchContent)
  835. FetchContent_Declare(
  836. projD
  837. GIT_REPOSITORY [email protected]:git/projD.git
  838. GIT_TAG 7d9a17ad2c962aa13e2fbb8043fb6b8a
  839. )
  840. # This particular version of projD requires workarounds
  841. FetchContent_GetProperties(projD)
  842. if(NOT projd_POPULATED)
  843. FetchContent_Populate(projD)
  844. # Copy an additional/replacement file into the populated source
  845. file(COPY someFile.c DESTINATION ${projd_SOURCE_DIR}/src)
  846. add_subdirectory(${projd_SOURCE_DIR} ${projd_BINARY_DIR})
  847. endif()
  848. A few key points should be noted in the above:
  849. - ``projB`` and ``projC`` define different content details for ``projD``,
  850. but ``projA`` also defines a set of content details for ``projD``.
  851. Because ``projA`` will define them first, the details from ``projB`` and
  852. ``projC`` will not be used. The override details defined by ``projA``
  853. are not required to match either of those from ``projB`` or ``projC``, but
  854. it is up to the higher level project to ensure that the details it does
  855. define still make sense for the child projects.
  856. - In the ``projA`` call to :command:`FetchContent_MakeAvailable`, ``projD``
  857. is listed ahead of ``projB`` and ``projC`` to ensure that ``projA`` is in
  858. control of how ``projD`` is populated.
  859. - While ``projA`` defines content details for ``projE``, it does not need
  860. to explicitly call ``FetchContent_MakeAvailable(projE)`` or
  861. ``FetchContent_Populate(projD)`` itself. Instead, it leaves that to the
  862. child ``projB``. For higher level projects, it is often enough to just
  863. define the override content details and leave the actual population to the
  864. child projects. This saves repeating the same thing at each level of the
  865. project hierarchy unnecessarily.
  866. Populating Content Without Adding It To The Build
  867. """""""""""""""""""""""""""""""""""""""""""""""""
  868. Projects don't always need to add the populated content to the build.
  869. Sometimes the project just wants to make the downloaded content available at
  870. a predictable location. The next example ensures that a set of standard
  871. company toolchain files (and potentially even the toolchain binaries
  872. themselves) is available early enough to be used for that same build.
  873. .. code-block:: cmake
  874. cmake_minimum_required(VERSION 3.14)
  875. include(FetchContent)
  876. FetchContent_Declare(
  877. mycom_toolchains
  878. URL https://intranet.mycompany.com//toolchains_1.3.2.tar.gz
  879. )
  880. FetchContent_MakeAvailable(mycom_toolchains)
  881. project(CrossCompileExample)
  882. The project could be configured to use one of the downloaded toolchains like
  883. so:
  884. .. code-block:: shell
  885. cmake -DCMAKE_TOOLCHAIN_FILE=_deps/mycom_toolchains-src/toolchain_arm.cmake /path/to/src
  886. When CMake processes the ``CMakeLists.txt`` file, it will download and unpack
  887. the tarball into ``_deps/mycompany_toolchains-src`` relative to the build
  888. directory. The :variable:`CMAKE_TOOLCHAIN_FILE` variable is not used until
  889. the :command:`project` command is reached, at which point CMake looks for the
  890. named toolchain file relative to the build directory. Because the tarball has
  891. already been downloaded and unpacked by then, the toolchain file will be in
  892. place, even the very first time that :program:`cmake` is run in the build directory.
  893. Populating Content In CMake Script Mode
  894. """""""""""""""""""""""""""""""""""""""
  895. This last example demonstrates how one might download and unpack a
  896. firmware tarball using CMake's :manual:`script mode <cmake(1)>`. The call to
  897. :command:`FetchContent_Populate` specifies all the content details and the
  898. unpacked firmware will be placed in a ``firmware`` directory below the
  899. current working directory.
  900. .. code-block:: cmake
  901. :caption: :file:`getFirmware.cmake`
  902. # NOTE: Intended to be run in script mode with cmake -P
  903. include(FetchContent)
  904. FetchContent_Populate(
  905. firmware
  906. URL https://mycompany.com/assets/firmware-1.23-arm.tar.gz
  907. URL_HASH MD5=68247684da89b608d466253762b0ff11
  908. SOURCE_DIR firmware
  909. )
  910. #]=======================================================================]
  911. include(${CMAKE_CURRENT_LIST_DIR}/ExternalProject/shared_internal_commands.cmake)
  912. #=======================================================================
  913. # Recording and retrieving content details for later population
  914. #=======================================================================
  915. # Internal use, projects must not call this directly. It is
  916. # intended for use by FetchContent_Declare() only.
  917. #
  918. # Sets a content-specific global property (not meant for use
  919. # outside of functions defined here in this file) which can later
  920. # be retrieved using __FetchContent_getSavedDetails() with just the
  921. # same content name. If there is already a value stored in the
  922. # property, it is left unchanged and this call has no effect.
  923. # This allows parent projects to define the content details,
  924. # overriding anything a child project may try to set (properties
  925. # are not cached between runs, so the first thing to set it in a
  926. # build will be in control).
  927. function(__FetchContent_declareDetails contentName)
  928. string(TOLOWER ${contentName} contentNameLower)
  929. set(savedDetailsPropertyName "_FetchContent_${contentNameLower}_savedDetails")
  930. get_property(alreadyDefined GLOBAL PROPERTY ${savedDetailsPropertyName} DEFINED)
  931. if(alreadyDefined)
  932. return()
  933. endif()
  934. if("${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}" STREQUAL "ALWAYS")
  935. set(__tryFindPackage TRUE)
  936. set(__tryFindPackageAllowed TRUE)
  937. elseif("${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}" STREQUAL "NEVER")
  938. set(__tryFindPackage FALSE)
  939. set(__tryFindPackageAllowed FALSE)
  940. elseif("${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}" STREQUAL "OPT_IN" OR
  941. NOT DEFINED FETCHCONTENT_TRY_FIND_PACKAGE_MODE)
  942. set(__tryFindPackage FALSE)
  943. set(__tryFindPackageAllowed TRUE)
  944. else()
  945. message(FATAL_ERROR
  946. "Unsupported value for FETCHCONTENT_TRY_FIND_PACKAGE_MODE: "
  947. "${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}"
  948. )
  949. endif()
  950. set(__cmdArgs)
  951. set(__findPackageArgs)
  952. set(__sawQuietKeyword NO)
  953. set(__sawGlobalKeyword NO)
  954. foreach(__item IN LISTS ARGN)
  955. if(DEFINED __findPackageArgs)
  956. # All remaining args are for find_package()
  957. string(APPEND __findPackageArgs " [==[${__item}]==]")
  958. if(__item STREQUAL "QUIET")
  959. set(__sawQuietKeyword YES)
  960. elseif(__item STREQUAL "GLOBAL")
  961. set(__sawGlobalKeyword YES)
  962. endif()
  963. continue()
  964. endif()
  965. # Still processing non-find_package() args
  966. if(__item STREQUAL "FIND_PACKAGE_ARGS")
  967. if(__tryFindPackageAllowed)
  968. set(__tryFindPackage TRUE)
  969. endif()
  970. # All arguments after this keyword are for find_package(). Define the
  971. # variable but with an empty value initially. This allows us to check
  972. # at the start of the loop whether to store remaining items in this
  973. # variable or not. Note that there could be no more args, which is still
  974. # a valid case because we automatically provide ${contentName} as the
  975. # package name and there may not need to be any further arguments.
  976. set(__findPackageArgs "")
  977. continue() # Don't store this item
  978. elseif(__item STREQUAL "OVERRIDE_FIND_PACKAGE")
  979. set(__tryFindPackageAllowed FALSE)
  980. # Define a separate dedicated property for find_package() to check
  981. # in its implementation. This will be a placeholder until FetchContent
  982. # actually does the population. After that, we will have created a
  983. # stand-in config file that find_package() will pick up instead.
  984. set(propertyName "_FetchContent_${contentNameLower}_override_find_package")
  985. define_property(GLOBAL PROPERTY ${propertyName})
  986. set_property(GLOBAL PROPERTY ${propertyName} TRUE)
  987. endif()
  988. string(APPEND __cmdArgs " [==[${__item}]==]")
  989. endforeach()
  990. define_property(GLOBAL PROPERTY ${savedDetailsPropertyName})
  991. cmake_language(EVAL CODE
  992. "set_property(GLOBAL PROPERTY ${savedDetailsPropertyName} ${__cmdArgs})"
  993. )
  994. if(__tryFindPackage AND __tryFindPackageAllowed)
  995. set(propertyName "_FetchContent_${contentNameLower}_find_package_args")
  996. define_property(GLOBAL PROPERTY ${propertyName})
  997. if(NOT __sawQuietKeyword)
  998. string(PREPEND __findPackageArgs "QUIET ")
  999. endif()
  1000. if(CMAKE_FIND_PACKAGE_TARGETS_GLOBAL AND NOT __sawGlobalKeyword)
  1001. string(APPEND __findPackageArgs " GLOBAL")
  1002. endif()
  1003. cmake_language(EVAL CODE
  1004. "set_property(GLOBAL PROPERTY ${propertyName} ${__findPackageArgs})"
  1005. )
  1006. endif()
  1007. endfunction()
  1008. # Internal use, projects must not call this directly. It is
  1009. # intended for use by the FetchContent_Declare() function.
  1010. #
  1011. # Retrieves details saved for the specified content in an
  1012. # earlier call to __FetchContent_declareDetails().
  1013. function(__FetchContent_getSavedDetails contentName outVar)
  1014. string(TOLOWER ${contentName} contentNameLower)
  1015. set(propertyName "_FetchContent_${contentNameLower}_savedDetails")
  1016. get_property(alreadyDefined GLOBAL PROPERTY ${propertyName} DEFINED)
  1017. if(NOT alreadyDefined)
  1018. message(FATAL_ERROR "No content details recorded for ${contentName}")
  1019. endif()
  1020. get_property(propertyValue GLOBAL PROPERTY ${propertyName})
  1021. set(${outVar} "${propertyValue}" PARENT_SCOPE)
  1022. endfunction()
  1023. # Saves population details of the content, sets defaults for the
  1024. # SOURCE_DIR and BUILD_DIR.
  1025. function(FetchContent_Declare contentName)
  1026. # Always check this even if we won't save these details.
  1027. # This helps projects catch errors earlier.
  1028. # Avoid using if(... IN_LIST ...) so we don't have to alter policy settings
  1029. list(FIND ARGN OVERRIDE_FIND_PACKAGE index_OVERRIDE_FIND_PACKAGE)
  1030. list(FIND ARGN FIND_PACKAGE_ARGS index_FIND_PACKAGE_ARGS)
  1031. if(index_OVERRIDE_FIND_PACKAGE GREATER_EQUAL 0 AND
  1032. index_FIND_PACKAGE_ARGS GREATER_EQUAL 0)
  1033. message(FATAL_ERROR
  1034. "Cannot specify both OVERRIDE_FIND_PACKAGE and FIND_PACKAGE_ARGS "
  1035. "when declaring details for ${contentName}"
  1036. )
  1037. endif()
  1038. # Because we are only looking for a subset of the supported keywords, we
  1039. # cannot check for multi-value arguments with this method. We will have to
  1040. # handle the URL keyword differently.
  1041. set(oneValueArgs
  1042. GIT_REPOSITORY
  1043. SVN_REPOSITORY
  1044. DOWNLOAD_NO_EXTRACT
  1045. DOWNLOAD_EXTRACT_TIMESTAMP
  1046. BINARY_DIR
  1047. SOURCE_DIR
  1048. )
  1049. cmake_parse_arguments(PARSE_ARGV 1 ARG "" "${oneValueArgs}" "")
  1050. string(TOLOWER ${contentName} contentNameLower)
  1051. if(NOT ARG_BINARY_DIR)
  1052. set(ARG_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
  1053. endif()
  1054. if(NOT ARG_SOURCE_DIR)
  1055. set(ARG_SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src")
  1056. endif()
  1057. if(ARG_GIT_REPOSITORY)
  1058. # We resolve the GIT_REPOSITORY here so that we get the right parent in the
  1059. # remote selection logic. In the sub-build, ExternalProject_Add() would see
  1060. # the private sub-build directory as the parent project, but the parent
  1061. # project should be the one that called FetchContent_Declare(). We resolve
  1062. # a relative repo here so that the sub-build's ExternalProject_Add() only
  1063. # ever sees a non-relative repo.
  1064. # Since these checks may be non-trivial on some platforms (notably Windows),
  1065. # don't perform them if we won't be using these details. This also allows
  1066. # projects to override calls with relative URLs when they have checked out
  1067. # the parent project in an unexpected way, such as from a mirror or fork.
  1068. set(savedDetailsPropertyName "_FetchContent_${contentNameLower}_savedDetails")
  1069. get_property(alreadyDefined GLOBAL PROPERTY ${savedDetailsPropertyName} DEFINED)
  1070. if(NOT alreadyDefined)
  1071. cmake_policy(GET CMP0150 cmp0150
  1072. PARENT_SCOPE # undocumented, do not use outside of CMake
  1073. )
  1074. _ep_resolve_git_remote(_resolved_git_repository
  1075. "${ARG_GIT_REPOSITORY}" "${cmp0150}" "${FETCHCONTENT_BASE_DIR}"
  1076. )
  1077. set(ARG_GIT_REPOSITORY "${_resolved_git_repository}")
  1078. endif()
  1079. endif()
  1080. if(ARG_SVN_REPOSITORY)
  1081. # Add a hash of the svn repository URL to the source dir. This works
  1082. # around the problem where if the URL changes, the download would
  1083. # fail because it tries to checkout/update rather than switch the
  1084. # old URL to the new one. We limit the hash to the first 7 characters
  1085. # so that the source path doesn't get overly long (which can be a
  1086. # problem on windows due to path length limits).
  1087. string(SHA1 urlSHA ${ARG_SVN_REPOSITORY})
  1088. string(SUBSTRING ${urlSHA} 0 7 urlSHA)
  1089. string(APPEND ARG_SOURCE_DIR "-${urlSHA}")
  1090. endif()
  1091. # The ExternalProject_Add() call in the sub-build won't see the CMP0135
  1092. # policy setting of our caller. Work out if that policy will be needed and
  1093. # explicitly set the relevant option if not already provided. The condition
  1094. # here is essentially an abbreviated version of the logic in
  1095. # ExternalProject's _ep_add_download_command() function.
  1096. if(NOT ARG_DOWNLOAD_NO_EXTRACT AND
  1097. NOT DEFINED ARG_DOWNLOAD_EXTRACT_TIMESTAMP)
  1098. list(FIND ARGN URL urlIndex)
  1099. if(urlIndex GREATER_EQUAL 0)
  1100. math(EXPR urlIndex "${urlIndex} + 1")
  1101. list(LENGTH ARGN numArgs)
  1102. if(urlIndex GREATER_EQUAL numArgs)
  1103. message(FATAL_ERROR
  1104. "URL keyword needs to be followed by at least one URL"
  1105. )
  1106. endif()
  1107. # If we have multiple URLs, none of them are allowed to be local paths.
  1108. # Therefore, we can test just the first URL, and if it is non-local, so
  1109. # will be the others if there are more.
  1110. list(GET ARGN ${urlIndex} firstUrl)
  1111. if(NOT IS_DIRECTORY "${firstUrl}")
  1112. cmake_policy(GET CMP0135 _FETCHCONTENT_CMP0135
  1113. PARENT_SCOPE # undocumented, do not use outside of CMake
  1114. )
  1115. if(_FETCHCONTENT_CMP0135 STREQUAL "")
  1116. message(AUTHOR_WARNING
  1117. "The DOWNLOAD_EXTRACT_TIMESTAMP option was not given and policy "
  1118. "CMP0135 is not set. The policy's OLD behavior will be used. "
  1119. "When using a URL download, the timestamps of extracted files "
  1120. "should preferably be that of the time of extraction, otherwise "
  1121. "code that depends on the extracted contents might not be "
  1122. "rebuilt if the URL changes. The OLD behavior preserves the "
  1123. "timestamps from the archive instead, but this is usually not "
  1124. "what you want. Update your project to the NEW behavior or "
  1125. "specify the DOWNLOAD_EXTRACT_TIMESTAMP option with a value of "
  1126. "true to avoid this robustness issue."
  1127. )
  1128. set(ARG_DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
  1129. elseif(_FETCHCONTENT_CMP0135 STREQUAL "NEW")
  1130. set(ARG_DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
  1131. else()
  1132. set(ARG_DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
  1133. endif()
  1134. endif()
  1135. endif()
  1136. endif()
  1137. # Add back in the keyword args we pulled out and potentially tweaked/added
  1138. set(sep EXTERNALPROJECT_INTERNAL_ARGUMENT_SEPARATOR)
  1139. foreach(key IN LISTS oneValueArgs)
  1140. if(DEFINED ARG_${key})
  1141. list(PREPEND ARG_UNPARSED_ARGUMENTS ${key} "${ARG_${key}}" ${sep})
  1142. set(sep "")
  1143. endif()
  1144. endforeach()
  1145. set(__argsQuoted)
  1146. foreach(__item IN LISTS ARG_UNPARSED_ARGUMENTS)
  1147. string(APPEND __argsQuoted " [==[${__item}]==]")
  1148. endforeach()
  1149. cmake_language(EVAL CODE
  1150. "__FetchContent_declareDetails(${contentNameLower} ${__argsQuoted})"
  1151. )
  1152. endfunction()
  1153. #=======================================================================
  1154. # Set/get whether the specified content has been populated yet.
  1155. # The setter also records the source and binary dirs used.
  1156. #=======================================================================
  1157. # Semi-internal use. Projects must not call this directly. Dependency
  1158. # providers must call it if they satisfy a request made with the
  1159. # FETCHCONTENT_MAKEAVAILABLE_SERIAL method (that is the only permitted
  1160. # place to call it outside of the FetchContent module).
  1161. function(FetchContent_SetPopulated contentName)
  1162. cmake_parse_arguments(PARSE_ARGV 1 arg
  1163. ""
  1164. "SOURCE_DIR;BINARY_DIR"
  1165. ""
  1166. )
  1167. if(NOT "${arg_UNPARSED_ARGUMENTS}" STREQUAL "")
  1168. message(FATAL_ERROR "Unsupported arguments: ${arg_UNPARSED_ARGUMENTS}")
  1169. endif()
  1170. string(TOLOWER ${contentName} contentNameLower)
  1171. set(prefix "_FetchContent_${contentNameLower}")
  1172. set(propertyName "${prefix}_sourceDir")
  1173. define_property(GLOBAL PROPERTY ${propertyName})
  1174. if("${arg_SOURCE_DIR}" STREQUAL "")
  1175. # Don't discard a previously provided SOURCE_DIR
  1176. get_property(arg_SOURCE_DIR GLOBAL PROPERTY ${propertyName})
  1177. endif()
  1178. set_property(GLOBAL PROPERTY ${propertyName} "${arg_SOURCE_DIR}")
  1179. set(propertyName "${prefix}_binaryDir")
  1180. define_property(GLOBAL PROPERTY ${propertyName})
  1181. if("${arg_BINARY_DIR}" STREQUAL "")
  1182. # Don't discard a previously provided BINARY_DIR
  1183. get_property(arg_BINARY_DIR GLOBAL PROPERTY ${propertyName})
  1184. endif()
  1185. set_property(GLOBAL PROPERTY ${propertyName} "${arg_BINARY_DIR}")
  1186. set(propertyName "${prefix}_populated")
  1187. define_property(GLOBAL PROPERTY ${propertyName})
  1188. set_property(GLOBAL PROPERTY ${propertyName} TRUE)
  1189. endfunction()
  1190. # Set variables in the calling scope for any of the retrievable
  1191. # properties. If no specific properties are requested, variables
  1192. # will be set for all retrievable properties.
  1193. #
  1194. # This function is intended to also be used by projects as the canonical
  1195. # way to detect whether they should call FetchContent_Populate()
  1196. # and pull the populated source into the build with add_subdirectory(),
  1197. # if they are using the populated content in that way.
  1198. function(FetchContent_GetProperties contentName)
  1199. string(TOLOWER ${contentName} contentNameLower)
  1200. set(options "")
  1201. set(oneValueArgs SOURCE_DIR BINARY_DIR POPULATED)
  1202. set(multiValueArgs "")
  1203. cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
  1204. if(NOT ARG_SOURCE_DIR AND
  1205. NOT ARG_BINARY_DIR AND
  1206. NOT ARG_POPULATED)
  1207. # No specific properties requested, provide them all
  1208. set(ARG_SOURCE_DIR ${contentNameLower}_SOURCE_DIR)
  1209. set(ARG_BINARY_DIR ${contentNameLower}_BINARY_DIR)
  1210. set(ARG_POPULATED ${contentNameLower}_POPULATED)
  1211. endif()
  1212. set(prefix "_FetchContent_${contentNameLower}")
  1213. if(ARG_SOURCE_DIR)
  1214. set(propertyName "${prefix}_sourceDir")
  1215. get_property(value GLOBAL PROPERTY ${propertyName})
  1216. if(value)
  1217. set(${ARG_SOURCE_DIR} ${value} PARENT_SCOPE)
  1218. endif()
  1219. endif()
  1220. if(ARG_BINARY_DIR)
  1221. set(propertyName "${prefix}_binaryDir")
  1222. get_property(value GLOBAL PROPERTY ${propertyName})
  1223. if(value)
  1224. set(${ARG_BINARY_DIR} ${value} PARENT_SCOPE)
  1225. endif()
  1226. endif()
  1227. if(ARG_POPULATED)
  1228. set(propertyName "${prefix}_populated")
  1229. get_property(value GLOBAL PROPERTY ${propertyName} DEFINED)
  1230. set(${ARG_POPULATED} ${value} PARENT_SCOPE)
  1231. endif()
  1232. endfunction()
  1233. #=======================================================================
  1234. # Performing the population
  1235. #=======================================================================
  1236. # The value of contentName will always have been lowercased by the caller.
  1237. # All other arguments are assumed to be options that are understood by
  1238. # ExternalProject_Add(), except for QUIET and SUBBUILD_DIR.
  1239. function(__FetchContent_directPopulate contentName)
  1240. set(options
  1241. QUIET
  1242. # EXCLUDE_FROM_ALL and SYSTEM have no meaning for ExternalProject, they
  1243. # are only used by us in FetchContent_MakeAvailable(). We need to parse
  1244. # and discard them here.
  1245. EXCLUDE_FROM_ALL
  1246. SYSTEM
  1247. )
  1248. set(oneValueArgs
  1249. SUBBUILD_DIR
  1250. SOURCE_DIR
  1251. BINARY_DIR
  1252. # We need special processing if DOWNLOAD_NO_EXTRACT is true
  1253. DOWNLOAD_NO_EXTRACT
  1254. # Prevent the following from being passed through
  1255. CONFIGURE_COMMAND
  1256. BUILD_COMMAND
  1257. INSTALL_COMMAND
  1258. TEST_COMMAND
  1259. # We force these to be ON since we are always executing serially
  1260. # and we want all steps to have access to the terminal in case they
  1261. # need input from the command line (e.g. ask for a private key password)
  1262. # or they want to provide timely progress. We silently absorb and
  1263. # discard these if they are set by the caller.
  1264. USES_TERMINAL_DOWNLOAD
  1265. USES_TERMINAL_UPDATE
  1266. USES_TERMINAL_PATCH
  1267. )
  1268. set(multiValueArgs "")
  1269. cmake_parse_arguments(PARSE_ARGV 1 ARG
  1270. "${options}" "${oneValueArgs}" "${multiValueArgs}")
  1271. if(NOT ARG_SUBBUILD_DIR)
  1272. message(FATAL_ERROR "Internal error: SUBBUILD_DIR not set")
  1273. elseif(NOT IS_ABSOLUTE "${ARG_SUBBUILD_DIR}")
  1274. set(ARG_SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SUBBUILD_DIR}")
  1275. endif()
  1276. if(NOT ARG_SOURCE_DIR)
  1277. message(FATAL_ERROR "Internal error: SOURCE_DIR not set")
  1278. elseif(NOT IS_ABSOLUTE "${ARG_SOURCE_DIR}")
  1279. set(ARG_SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SOURCE_DIR}")
  1280. endif()
  1281. if(NOT ARG_BINARY_DIR)
  1282. message(FATAL_ERROR "Internal error: BINARY_DIR not set")
  1283. elseif(NOT IS_ABSOLUTE "${ARG_BINARY_DIR}")
  1284. set(ARG_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_BINARY_DIR}")
  1285. endif()
  1286. # Ensure the caller can know where to find the source and build directories
  1287. # with some convenient variables. Doing this here ensures the caller sees
  1288. # the correct result in the case where the default values are overridden by
  1289. # the content details set by the project.
  1290. set(${contentName}_SOURCE_DIR "${ARG_SOURCE_DIR}" PARENT_SCOPE)
  1291. set(${contentName}_BINARY_DIR "${ARG_BINARY_DIR}" PARENT_SCOPE)
  1292. # The unparsed arguments may contain spaces, so build up ARG_EXTRA
  1293. # in such a way that it correctly substitutes into the generated
  1294. # CMakeLists.txt file with each argument quoted.
  1295. unset(ARG_EXTRA)
  1296. foreach(arg IN LISTS ARG_UNPARSED_ARGUMENTS)
  1297. set(ARG_EXTRA "${ARG_EXTRA} \"${arg}\"")
  1298. endforeach()
  1299. if(ARG_DOWNLOAD_NO_EXTRACT)
  1300. set(ARG_EXTRA "${ARG_EXTRA} DOWNLOAD_NO_EXTRACT YES")
  1301. set(__FETCHCONTENT_COPY_FILE
  1302. "
  1303. ExternalProject_Get_Property(${contentName}-populate DOWNLOADED_FILE)
  1304. get_filename_component(dlFileName \"\${DOWNLOADED_FILE}\" NAME)
  1305. ExternalProject_Add_Step(${contentName}-populate copyfile
  1306. COMMAND \"${CMAKE_COMMAND}\" -E copy_if_different
  1307. \"<DOWNLOADED_FILE>\" \"${ARG_SOURCE_DIR}\"
  1308. DEPENDEES patch
  1309. DEPENDERS configure
  1310. BYPRODUCTS \"${ARG_SOURCE_DIR}/\${dlFileName}\"
  1311. COMMENT \"Copying file to SOURCE_DIR\"
  1312. )
  1313. ")
  1314. else()
  1315. unset(__FETCHCONTENT_COPY_FILE)
  1316. endif()
  1317. # Hide output if requested, but save it to a variable in case there's an
  1318. # error so we can show the output upon failure. When not quiet, don't
  1319. # capture the output to a variable because the user may want to see the
  1320. # output as it happens (e.g. progress during long downloads). Combine both
  1321. # stdout and stderr in the one capture variable so the output stays in order.
  1322. if (ARG_QUIET)
  1323. set(outputOptions
  1324. OUTPUT_VARIABLE capturedOutput
  1325. ERROR_VARIABLE capturedOutput
  1326. )
  1327. else()
  1328. set(capturedOutput)
  1329. set(outputOptions)
  1330. message(STATUS "Populating ${contentName}")
  1331. endif()
  1332. if(CMAKE_GENERATOR)
  1333. set(subCMakeOpts "-G${CMAKE_GENERATOR}")
  1334. if(CMAKE_GENERATOR_PLATFORM)
  1335. list(APPEND subCMakeOpts "-A${CMAKE_GENERATOR_PLATFORM}")
  1336. endif()
  1337. if(CMAKE_GENERATOR_TOOLSET)
  1338. list(APPEND subCMakeOpts "-T${CMAKE_GENERATOR_TOOLSET}")
  1339. endif()
  1340. if(CMAKE_GENERATOR_INSTANCE)
  1341. list(APPEND subCMakeOpts "-DCMAKE_GENERATOR_INSTANCE:INTERNAL=${CMAKE_GENERATOR_INSTANCE}")
  1342. endif()
  1343. if(CMAKE_MAKE_PROGRAM)
  1344. list(APPEND subCMakeOpts "-DCMAKE_MAKE_PROGRAM:FILEPATH=${CMAKE_MAKE_PROGRAM}")
  1345. endif()
  1346. # GreenHills needs to know about the compiler and toolset to run the
  1347. # subbuild commands. Be sure to update the similar section in
  1348. # ExternalProject.cmake:_ep_extract_configure_command()
  1349. if(CMAKE_GENERATOR MATCHES "Green Hills MULTI")
  1350. list(APPEND subCMakeOpts
  1351. "-DGHS_TARGET_PLATFORM:STRING=${GHS_TARGET_PLATFORM}"
  1352. "-DGHS_PRIMARY_TARGET:STRING=${GHS_PRIMARY_TARGET}"
  1353. "-DGHS_TOOLSET_ROOT:STRING=${GHS_TOOLSET_ROOT}"
  1354. "-DGHS_OS_ROOT:STRING=${GHS_OS_ROOT}"
  1355. "-DGHS_OS_DIR:STRING=${GHS_OS_DIR}"
  1356. "-DGHS_BSP_NAME:STRING=${GHS_BSP_NAME}"
  1357. )
  1358. endif()
  1359. # Override the sub-build's configuration types for multi-config generators.
  1360. # This ensures we are not affected by any custom setting from the project
  1361. # and can always request a known configuration further below.
  1362. get_property(is_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
  1363. if(is_multi_config)
  1364. list(APPEND subCMakeOpts "-DCMAKE_CONFIGURATION_TYPES:STRING=Debug")
  1365. endif()
  1366. else()
  1367. # Likely we've been invoked via CMake's script mode where no
  1368. # generator is set (and hence CMAKE_MAKE_PROGRAM could not be
  1369. # trusted even if provided). We will have to rely on being
  1370. # able to find the default generator and build tool.
  1371. unset(subCMakeOpts)
  1372. endif()
  1373. set(__FETCHCONTENT_CACHED_INFO "")
  1374. set(__passthrough_vars
  1375. CMAKE_EP_GIT_REMOTE_UPDATE_STRATEGY
  1376. CMAKE_TLS_VERIFY
  1377. CMAKE_TLS_CAINFO
  1378. CMAKE_NETRC
  1379. CMAKE_NETRC_FILE
  1380. )
  1381. foreach(var IN LISTS __passthrough_vars)
  1382. if(DEFINED ${var})
  1383. # Embed directly in the generated CMakeLists.txt file to avoid making
  1384. # the cmake command line excessively long. It also makes debugging and
  1385. # testing easier.
  1386. string(APPEND __FETCHCONTENT_CACHED_INFO "set(${var} [==[${${var}}]==])\n")
  1387. endif()
  1388. endforeach()
  1389. # Avoid using if(... IN_LIST ...) so we don't have to alter policy settings
  1390. list(FIND ARG_UNPARSED_ARGUMENTS GIT_REPOSITORY indexResult)
  1391. if(indexResult GREATER_EQUAL 0)
  1392. find_package(Git QUIET)
  1393. string(APPEND __FETCHCONTENT_CACHED_INFO "
  1394. # Pass through things we've already detected in the main project to avoid
  1395. # paying the cost of redetecting them again in ExternalProject_Add()
  1396. set(GIT_EXECUTABLE [==[${GIT_EXECUTABLE}]==])
  1397. set(GIT_VERSION_STRING [==[${GIT_VERSION_STRING}]==])
  1398. set_property(GLOBAL PROPERTY _CMAKE_FindGit_GIT_EXECUTABLE_VERSION
  1399. [==[${GIT_EXECUTABLE};${GIT_VERSION_STRING}]==]
  1400. )
  1401. ")
  1402. endif()
  1403. # Create and build a separate CMake project to carry out the population.
  1404. # If we've already previously done these steps, they will not cause
  1405. # anything to be updated, so extra rebuilds of the project won't occur.
  1406. # Make sure to pass through CMAKE_MAKE_PROGRAM in case the main project
  1407. # has this set to something not findable on the PATH. We also ensured above
  1408. # that the Debug config will be defined for multi-config generators.
  1409. configure_file("${CMAKE_CURRENT_FUNCTION_LIST_DIR}/FetchContent/CMakeLists.cmake.in"
  1410. "${ARG_SUBBUILD_DIR}/CMakeLists.txt"
  1411. @ONLY
  1412. )
  1413. execute_process(
  1414. COMMAND ${CMAKE_COMMAND} ${subCMakeOpts} .
  1415. RESULT_VARIABLE result
  1416. ${outputOptions}
  1417. WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
  1418. )
  1419. if(result)
  1420. if(capturedOutput)
  1421. message("${capturedOutput}")
  1422. endif()
  1423. message(FATAL_ERROR "CMake step for ${contentName} failed: ${result}")
  1424. endif()
  1425. execute_process(
  1426. COMMAND ${CMAKE_COMMAND} --build . --config Debug
  1427. RESULT_VARIABLE result
  1428. ${outputOptions}
  1429. WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
  1430. )
  1431. if(result)
  1432. if(capturedOutput)
  1433. message("${capturedOutput}")
  1434. endif()
  1435. message(FATAL_ERROR "Build step for ${contentName} failed: ${result}")
  1436. endif()
  1437. endfunction()
  1438. option(FETCHCONTENT_FULLY_DISCONNECTED "Disables all attempts to download or update content and assumes source dirs already exist")
  1439. option(FETCHCONTENT_UPDATES_DISCONNECTED "Enables UPDATE_DISCONNECTED behavior for all content population")
  1440. option(FETCHCONTENT_QUIET "Enables QUIET option for all content population" ON)
  1441. set(FETCHCONTENT_BASE_DIR "${CMAKE_BINARY_DIR}/_deps" CACHE PATH "Directory under which to collect all populated content")
  1442. # Populate the specified content using details stored from
  1443. # an earlier call to FetchContent_Declare().
  1444. function(FetchContent_Populate contentName)
  1445. if(NOT contentName)
  1446. message(FATAL_ERROR "Empty contentName not allowed for FetchContent_Populate()")
  1447. endif()
  1448. string(TOLOWER ${contentName} contentNameLower)
  1449. if(ARGN)
  1450. # This is the direct population form with details fully specified
  1451. # as part of the call, so we already have everything we need
  1452. __FetchContent_directPopulate(
  1453. ${contentNameLower}
  1454. SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-subbuild"
  1455. SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-src"
  1456. BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-build"
  1457. ${ARGN} # Could override any of the above ..._DIR variables
  1458. )
  1459. # Pass source and binary dir variables back to the caller
  1460. set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
  1461. set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
  1462. # Don't set global properties, or record that we did this population, since
  1463. # this was a direct call outside of the normal declared details form.
  1464. # We only want to save values in the global properties for content that
  1465. # honors the hierarchical details mechanism so that projects are not
  1466. # robbed of the ability to override details set in nested projects.
  1467. return()
  1468. endif()
  1469. # No details provided, so assume they were saved from an earlier call
  1470. # to FetchContent_Declare(). Do a check that we haven't already
  1471. # populated this content before in case the caller forgot to check.
  1472. FetchContent_GetProperties(${contentName})
  1473. if(${contentNameLower}_POPULATED)
  1474. if("${${contentNameLower}_SOURCE_DIR}" STREQUAL "")
  1475. message(FATAL_ERROR
  1476. "Content ${contentName} already populated by find_package() or a "
  1477. "dependency provider"
  1478. )
  1479. else()
  1480. message(FATAL_ERROR
  1481. "Content ${contentName} already populated in ${${contentNameLower}_SOURCE_DIR}"
  1482. )
  1483. endif()
  1484. endif()
  1485. __FetchContent_getSavedDetails(${contentName} contentDetails)
  1486. if("${contentDetails}" STREQUAL "")
  1487. message(FATAL_ERROR "No details have been set for content: ${contentName}")
  1488. endif()
  1489. string(TOUPPER ${contentName} contentNameUpper)
  1490. set(FETCHCONTENT_SOURCE_DIR_${contentNameUpper}
  1491. "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}"
  1492. CACHE PATH "When not empty, overrides where to find pre-populated content for ${contentName}")
  1493. if(FETCHCONTENT_SOURCE_DIR_${contentNameUpper})
  1494. # The source directory has been explicitly provided in the cache,
  1495. # so no population is required. The build directory may still be specified
  1496. # by the declared details though.
  1497. if(NOT IS_ABSOLUTE "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  1498. # Don't check this directory because we don't know what location it is
  1499. # expected to be relative to. We can't make this a hard error for backward
  1500. # compatibility reasons.
  1501. message(WARNING "Relative source directory specified. This is not safe, "
  1502. "as it depends on the calling directory scope.\n"
  1503. " FETCHCONTENT_SOURCE_DIR_${contentNameUpper} --> ${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  1504. elseif(NOT EXISTS "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  1505. message(FATAL_ERROR "Manually specified source directory is missing:\n"
  1506. " FETCHCONTENT_SOURCE_DIR_${contentNameUpper} --> ${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  1507. endif()
  1508. set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
  1509. cmake_parse_arguments(savedDetails "" "BINARY_DIR" "" ${contentDetails})
  1510. if(savedDetails_BINARY_DIR)
  1511. set(${contentNameLower}_BINARY_DIR ${savedDetails_BINARY_DIR})
  1512. else()
  1513. set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
  1514. endif()
  1515. elseif(FETCHCONTENT_FULLY_DISCONNECTED)
  1516. # Bypass population and assume source is already there from a previous run.
  1517. # Declared details may override the default source or build directories.
  1518. cmake_parse_arguments(savedDetails "" "SOURCE_DIR;BINARY_DIR" "" ${contentDetails})
  1519. if(savedDetails_SOURCE_DIR)
  1520. set(${contentNameLower}_SOURCE_DIR ${savedDetails_SOURCE_DIR})
  1521. else()
  1522. set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src")
  1523. endif()
  1524. if(savedDetails_BINARY_DIR)
  1525. set(${contentNameLower}_BINARY_DIR ${savedDetails_BINARY_DIR})
  1526. else()
  1527. set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
  1528. endif()
  1529. else()
  1530. # Support both a global "disconnect all updates" and a per-content
  1531. # update test (either one being set disables updates for this content).
  1532. option(FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper}
  1533. "Enables UPDATE_DISCONNECTED behavior just for population of ${contentName}")
  1534. if(FETCHCONTENT_UPDATES_DISCONNECTED OR
  1535. FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper})
  1536. set(disconnectUpdates True)
  1537. else()
  1538. set(disconnectUpdates False)
  1539. endif()
  1540. if(FETCHCONTENT_QUIET)
  1541. set(quietFlag QUIET)
  1542. else()
  1543. unset(quietFlag)
  1544. endif()
  1545. set(__detailsQuoted)
  1546. foreach(__item IN LISTS contentDetails)
  1547. if(NOT __item STREQUAL "OVERRIDE_FIND_PACKAGE")
  1548. string(APPEND __detailsQuoted " [==[${__item}]==]")
  1549. endif()
  1550. endforeach()
  1551. cmake_language(EVAL CODE "
  1552. __FetchContent_directPopulate(
  1553. ${contentNameLower}
  1554. ${quietFlag}
  1555. UPDATE_DISCONNECTED ${disconnectUpdates}
  1556. SUBBUILD_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-subbuild\"
  1557. SOURCE_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src\"
  1558. BINARY_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build\"
  1559. # Put the saved details last so they can override any of the
  1560. # the options we set above (this can include SOURCE_DIR or
  1561. # BUILD_DIR)
  1562. ${__detailsQuoted}
  1563. )"
  1564. )
  1565. endif()
  1566. FetchContent_SetPopulated(
  1567. ${contentName}
  1568. SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}"
  1569. BINARY_DIR "${${contentNameLower}_BINARY_DIR}"
  1570. )
  1571. # Pass variables back to the caller. The variables passed back here
  1572. # must match what FetchContent_GetProperties() sets when it is called
  1573. # with just the content name.
  1574. set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
  1575. set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
  1576. set(${contentNameLower}_POPULATED True PARENT_SCOPE)
  1577. endfunction()
  1578. function(__FetchContent_setupFindPackageRedirection contentName)
  1579. __FetchContent_getSavedDetails(${contentName} contentDetails)
  1580. string(TOLOWER ${contentName} contentNameLower)
  1581. get_property(wantFindPackage GLOBAL PROPERTY
  1582. _FetchContent_${contentNameLower}_find_package_args
  1583. DEFINED
  1584. )
  1585. # Avoid using if(... IN_LIST ...) so we don't have to alter policy settings
  1586. list(FIND contentDetails OVERRIDE_FIND_PACKAGE indexResult)
  1587. if(NOT wantFindPackage AND indexResult EQUAL -1)
  1588. # No find_package() redirection allowed
  1589. return()
  1590. endif()
  1591. # We write out dep-config.cmake and dep-config-version.cmake file name
  1592. # forms here because they are forced to lowercase. FetchContent
  1593. # dependency names are case-insensitive, but find_package() config files
  1594. # are only case-insensitive for the -config and -config-version forms,
  1595. # not the Config and ConfigVersion forms.
  1596. set(inFileDir ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/FetchContent)
  1597. set(configFilePrefix1 "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/${contentName}Config")
  1598. set(configFilePrefix2 "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/${contentNameLower}-config")
  1599. if(NOT EXISTS "${configFilePrefix1}.cmake" AND
  1600. NOT EXISTS "${configFilePrefix2}.cmake")
  1601. configure_file(${inFileDir}/package-config.cmake.in
  1602. "${configFilePrefix2}.cmake" @ONLY
  1603. )
  1604. endif()
  1605. if(NOT EXISTS "${configFilePrefix1}Version.cmake" AND
  1606. NOT EXISTS "${configFilePrefix2}-version.cmake")
  1607. configure_file(${inFileDir}/package-config-version.cmake.in
  1608. "${configFilePrefix2}-version.cmake" @ONLY
  1609. )
  1610. endif()
  1611. # Now that we've created the redirected package config files, prevent
  1612. # find_package() from delegating to FetchContent and let it find these
  1613. # config files through its normal processing.
  1614. set(propertyName "${prefix}_override_find_package")
  1615. set(GLOBAL PROPERTY ${propertyName} FALSE)
  1616. set(${contentName}_DIR "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}"
  1617. CACHE INTERNAL "Redirected by FetchContent"
  1618. )
  1619. endfunction()
  1620. # Arguments are assumed to be the names of dependencies that have been
  1621. # declared previously and should be populated. It is not an error if
  1622. # any of them have already been populated (they will just be skipped in
  1623. # that case). The command is implemented as a macro so that the variables
  1624. # defined by the FetchContent_GetProperties() and FetchContent_Populate()
  1625. # calls will be available to the caller.
  1626. macro(FetchContent_MakeAvailable)
  1627. # We must append an item, even if the variable is unset, so prefix its value.
  1628. # We will strip that prefix when we pop the value at the end of the macro.
  1629. list(APPEND __cmake_fcCurrentVarsStack
  1630. "__fcprefix__${CMAKE_VERIFY_INTERFACE_HEADER_SETS}"
  1631. )
  1632. set(CMAKE_VERIFY_INTERFACE_HEADER_SETS FALSE)
  1633. get_property(__cmake_providerCommand GLOBAL PROPERTY
  1634. __FETCHCONTENT_MAKEAVAILABLE_SERIAL_PROVIDER
  1635. )
  1636. foreach(__cmake_contentName IN ITEMS ${ARGV})
  1637. string(TOLOWER ${__cmake_contentName} __cmake_contentNameLower)
  1638. # If user specified FETCHCONTENT_SOURCE_DIR_... for this dependency, that
  1639. # overrides everything else and we shouldn't try to use find_package() or
  1640. # a dependency provider.
  1641. string(TOUPPER ${__cmake_contentName} __cmake_contentNameUpper)
  1642. if("${FETCHCONTENT_SOURCE_DIR_${__cmake_contentNameUpper}}" STREQUAL "")
  1643. # Dependency provider gets first opportunity, but prevent infinite
  1644. # recursion if we are called again for the same thing
  1645. if(NOT "${__cmake_providerCommand}" STREQUAL "" AND
  1646. NOT DEFINED __cmake_fcProvider_${__cmake_contentNameLower})
  1647. message(VERBOSE
  1648. "Trying FETCHCONTENT_MAKEAVAILABLE_SERIAL dependency provider for "
  1649. "${__cmake_contentName}"
  1650. )
  1651. list(APPEND __cmake_fcCurrentVarsStack "__fcprefix__${CMAKE_EXPORT_FIND_PACKAGE_NAME}")
  1652. set(CMAKE_EXPORT_FIND_PACKAGE_NAME "${__cmake_contentName}")
  1653. # It's still valid if there are no saved details. The project may have
  1654. # been written to assume a dependency provider is always set and will
  1655. # provide dependencies without having any declared details for them.
  1656. __FetchContent_getSavedDetails(${__cmake_contentName} __cmake_contentDetails)
  1657. set(__cmake_providerArgs
  1658. "FETCHCONTENT_MAKEAVAILABLE_SERIAL"
  1659. "${__cmake_contentName}"
  1660. )
  1661. # Empty arguments must be preserved because of things like
  1662. # GIT_SUBMODULES (see CMP0097)
  1663. foreach(__cmake_item IN LISTS __cmake_contentDetails)
  1664. string(APPEND __cmake_providerArgs " [==[${__cmake_item}]==]")
  1665. endforeach()
  1666. # This property might be defined but empty. As long as it is defined,
  1667. # find_package() can be called.
  1668. get_property(__cmake_addfpargs GLOBAL PROPERTY
  1669. _FetchContent_${contentNameLower}_find_package_args
  1670. DEFINED
  1671. )
  1672. if(__cmake_addfpargs)
  1673. get_property(__cmake_fpargs GLOBAL PROPERTY
  1674. _FetchContent_${contentNameLower}_find_package_args
  1675. )
  1676. string(APPEND __cmake_providerArgs " FIND_PACKAGE_ARGS")
  1677. foreach(__cmake_item IN LISTS __cmake_fpargs)
  1678. string(APPEND __cmake_providerArgs " [==[${__cmake_item}]==]")
  1679. endforeach()
  1680. endif()
  1681. # Calling the provider could lead to FetchContent_MakeAvailable() being
  1682. # called for a nested dependency. That nested call may occur in the
  1683. # current variable scope. We have to save and restore the variables we
  1684. # need preserved.
  1685. list(APPEND __cmake_fcCurrentVarsStack
  1686. ${__cmake_contentName}
  1687. ${__cmake_contentNameLower}
  1688. )
  1689. set(__cmake_fcProvider_${__cmake_contentNameLower} YES)
  1690. cmake_language(EVAL CODE "${__cmake_providerCommand}(${__cmake_providerArgs})")
  1691. list(POP_BACK __cmake_fcCurrentVarsStack
  1692. __cmake_contentNameLower
  1693. __cmake_contentName
  1694. )
  1695. unset(__cmake_fcProvider_${__cmake_contentNameLower})
  1696. unset(__cmake_providerArgs)
  1697. unset(__cmake_addfpargs)
  1698. unset(__cmake_fpargs)
  1699. unset(__cmake_item)
  1700. unset(__cmake_contentDetails)
  1701. list(POP_BACK __cmake_fcCurrentVarsStack __cmake_original_export_find_package_name)
  1702. string(SUBSTRING "${__cmake_original_export_find_package_name}"
  1703. 12 -1 __cmake_original_export_find_package_name
  1704. )
  1705. set(CMAKE_EXPORT_FIND_PACKAGE_NAME ${__cmake_original_export_find_package_name})
  1706. FetchContent_GetProperties(${__cmake_contentName})
  1707. if(${__cmake_contentNameLower}_POPULATED)
  1708. continue()
  1709. endif()
  1710. endif()
  1711. # Check if we've been asked to try find_package() first, even if we
  1712. # have already populated this dependency. If we previously tried to
  1713. # use find_package() for this and it succeeded, those things might
  1714. # no longer be in scope, so we have to do it again.
  1715. get_property(__cmake_haveFpArgs GLOBAL PROPERTY
  1716. _FetchContent_${__cmake_contentNameLower}_find_package_args DEFINED
  1717. )
  1718. if(__cmake_haveFpArgs)
  1719. unset(__cmake_haveFpArgs)
  1720. message(VERBOSE "Trying find_package(${__cmake_contentName} ...) before FetchContent")
  1721. get_property(__cmake_fpArgs GLOBAL PROPERTY
  1722. _FetchContent_${__cmake_contentNameLower}_find_package_args
  1723. )
  1724. # This call could lead to FetchContent_MakeAvailable() being called for
  1725. # a nested dependency and it may occur in the current variable scope.
  1726. # We have to save/restore the variables we need to preserve.
  1727. list(APPEND __cmake_fcCurrentNameStack
  1728. ${__cmake_contentName}
  1729. ${__cmake_contentNameLower}
  1730. )
  1731. find_package(${__cmake_contentName} ${__cmake_fpArgs})
  1732. list(POP_BACK __cmake_fcCurrentNameStack
  1733. __cmake_contentNameLower
  1734. __cmake_contentName
  1735. )
  1736. unset(__cmake_fpArgs)
  1737. if(${__cmake_contentName}_FOUND)
  1738. FetchContent_SetPopulated(${__cmake_contentName})
  1739. FetchContent_GetProperties(${__cmake_contentName})
  1740. continue()
  1741. endif()
  1742. endif()
  1743. else()
  1744. unset(__cmake_haveFpArgs)
  1745. endif()
  1746. FetchContent_GetProperties(${__cmake_contentName})
  1747. if(NOT ${__cmake_contentNameLower}_POPULATED)
  1748. FetchContent_Populate(${__cmake_contentName})
  1749. __FetchContent_setupFindPackageRedirection(${__cmake_contentName})
  1750. # Only try to call add_subdirectory() if the populated content
  1751. # can be treated that way. Protecting the call with the check
  1752. # allows this function to be used for projects that just want
  1753. # to ensure the content exists, such as to provide content at
  1754. # a known location. We check the saved details for an optional
  1755. # SOURCE_SUBDIR which can be used in the same way as its meaning
  1756. # for ExternalProject. It won't matter if it was passed through
  1757. # to the ExternalProject sub-build, since it would have been
  1758. # ignored there.
  1759. set(__cmake_srcdir "${${__cmake_contentNameLower}_SOURCE_DIR}")
  1760. __FetchContent_getSavedDetails(${__cmake_contentName} __cmake_contentDetails)
  1761. if("${__cmake_contentDetails}" STREQUAL "")
  1762. message(FATAL_ERROR "No details have been set for content: ${__cmake_contentName}")
  1763. endif()
  1764. cmake_parse_arguments(__cmake_arg "EXCLUDE_FROM_ALL;SYSTEM" "SOURCE_SUBDIR" "" ${__cmake_contentDetails})
  1765. if(NOT "${__cmake_arg_SOURCE_SUBDIR}" STREQUAL "")
  1766. string(APPEND __cmake_srcdir "/${__cmake_arg_SOURCE_SUBDIR}")
  1767. endif()
  1768. if(EXISTS ${__cmake_srcdir}/CMakeLists.txt)
  1769. list(APPEND __cmake_fcCurrentVarsStack "__fcprefix__${CMAKE_EXPORT_FIND_PACKAGE_NAME}")
  1770. set(CMAKE_EXPORT_FIND_PACKAGE_NAME "${__cmake_contentName}")
  1771. set(__cmake_add_subdirectory_args ${__cmake_srcdir} ${${__cmake_contentNameLower}_BINARY_DIR})
  1772. if(__cmake_arg_EXCLUDE_FROM_ALL)
  1773. list(APPEND __cmake_add_subdirectory_args EXCLUDE_FROM_ALL)
  1774. endif()
  1775. if(__cmake_arg_SYSTEM)
  1776. list(APPEND __cmake_add_subdirectory_args SYSTEM)
  1777. endif()
  1778. add_subdirectory(${__cmake_add_subdirectory_args})
  1779. list(POP_BACK __cmake_fcCurrentVarsStack __cmake_original_export_find_package_name)
  1780. string(SUBSTRING "${__cmake_original_export_find_package_name}"
  1781. 12 -1 __cmake_original_export_find_package_name
  1782. )
  1783. set(CMAKE_EXPORT_FIND_PACKAGE_NAME ${__cmake_original_export_find_package_name})
  1784. endif()
  1785. unset(__cmake_srcdir)
  1786. unset(__cmake_contentDetails)
  1787. unset(__cmake_arg_EXCLUDE_FROM_ALL)
  1788. unset(__cmake_arg_SYSTEM)
  1789. unset(__cmake_arg_SOURCE_SUBDIR)
  1790. unset(__cmake_add_subdirectory_args)
  1791. endif()
  1792. endforeach()
  1793. # Prefix will be "__fcprefix__"
  1794. list(POP_BACK __cmake_fcCurrentVarsStack __cmake_original_verify_setting)
  1795. string(SUBSTRING "${__cmake_original_verify_setting}"
  1796. 12 -1 __cmake_original_verify_setting
  1797. )
  1798. set(CMAKE_VERIFY_INTERFACE_HEADER_SETS ${__cmake_original_verify_setting})
  1799. # clear local variables to prevent leaking into the caller's scope
  1800. unset(__cmake_contentName)
  1801. unset(__cmake_contentNameLower)
  1802. unset(__cmake_contentNameUpper)
  1803. unset(__cmake_providerCommand)
  1804. unset(__cmake_original_verify_setting)
  1805. endmacro()