FetchContent.cmake 86 KB

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