FetchContent.cmake 97 KB

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