1 # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
2 # file Copyright.txt or https://cmake.org/licensing for details.
4 #[=======================================================================[.rst:
14 .. note:: The :guide:`Using Dependencies Guide` provides a high-level
15 introduction to this general topic. It provides a broader overview of
16 where the ``FetchContent`` module fits into the bigger picture,
17 including its relationship to the :command:`find_package` command.
18 The guide is recommended pre-reading before moving on to the details below.
23 This module enables populating content at configure time via any method
24 supported by the :module:`ExternalProject` module. Whereas
25 :command:`ExternalProject_Add` downloads at build time, the
26 ``FetchContent`` module makes content available immediately, allowing the
27 configure step to use the content in commands like :command:`add_subdirectory`,
28 :command:`include` or :command:`file` operations.
30 Content population details should be defined separately from the command that
31 performs the actual population. This separation ensures that all the
32 dependency details are defined before anything might try to use them to
33 populate content. This is particularly important in more complex project
34 hierarchies where dependencies may be shared between multiple projects.
36 The following shows a typical example of declaring content details for some
37 dependencies and then ensuring they are populated with a separate call:
43 GIT_REPOSITORY https://github.com/google/googletest.git
44 GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
48 URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
49 URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
52 FetchContent_MakeAvailable(googletest myCompanyIcons)
54 The :command:`FetchContent_MakeAvailable` command ensures the named
55 dependencies have been populated, either by an earlier call or by populating
56 them itself. When performing the population, it will also add them to the
57 main build, if possible, so that the main build can use the populated
58 projects' targets, etc. See the command's documentation for how these steps
61 When using a hierarchical project arrangement, projects at higher levels in
62 the hierarchy are able to override the declared details of content specified
63 anywhere lower in the project hierarchy. The first details to be declared
64 for a given dependency take precedence, regardless of where in the project
65 hierarchy that occurs. Similarly, the first call that tries to populate a
66 dependency "wins", with subsequent populations reusing the result of the
67 first instead of repeating the population again.
68 See the :ref:`Examples <fetch-content-examples>` which demonstrate
71 In some cases, the main project may need to have more precise control over
72 the population, or it may be required to explicitly define the population
73 steps in a way that cannot be captured by the declared details alone.
74 For such situations, the lower level :command:`FetchContent_GetProperties` and
75 :command:`FetchContent_Populate` commands can be used. These lack the richer
76 features provided by :command:`FetchContent_MakeAvailable` though, so their
77 direct use should be considered a last resort. The typical pattern of such
78 custom steps looks like this:
82 # NOTE: Where possible, prefer to use FetchContent_MakeAvailable()
83 # instead of custom logic like this
85 # Check if population has already been performed
86 FetchContent_GetProperties(depname)
87 if(NOT depname_POPULATED)
88 # Fetch the content using previously declared details
89 FetchContent_Populate(depname)
91 # Set custom variables, policies, etc.
94 # Bring the populated content into the build
95 add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
98 The ``FetchContent`` module also supports defining and populating
99 content in a single call, with no check for whether the content has been
100 populated elsewhere already. This should not be done in projects, but may
101 be appropriate for populating content in CMake's script mode.
102 See :command:`FetchContent_Populate` for details.
107 .. command:: FetchContent_Declare
109 .. code-block:: cmake
111 FetchContent_Declare(
114 [OVERRIDE_FIND_PACKAGE |
115 FIND_PACKAGE_ARGS args...]
118 The ``FetchContent_Declare()`` function records the options that describe
119 how to populate the specified content. If such details have already
120 been recorded earlier in this project (regardless of where in the project
121 hierarchy), this and all later calls for the same content ``<name>`` are
122 ignored. This "first to record, wins" approach is what allows hierarchical
123 projects to have parent projects override content details of child projects.
125 The content ``<name>`` can be any string without spaces, but good practice
126 would be to use only letters, numbers and underscores. The name will be
127 treated case-insensitively and it should be obvious for the content it
128 represents, often being the name of the child project or the value given
129 to its top level :command:`project` command (if it is a CMake project).
130 For well-known public projects, the name should generally be the official
131 name of the project. Choosing an unusual name makes it unlikely that other
132 projects needing that same content will use the same name, leading to
133 the content being populated multiple times.
135 The ``<contentOptions>`` can be any of the download, update or patch options
136 that the :command:`ExternalProject_Add` command understands. The configure,
137 build, install and test steps are explicitly disabled and therefore options
138 related to them will be ignored. The ``SOURCE_SUBDIR`` option is an
139 exception, see :command:`FetchContent_MakeAvailable` for details on how that
142 In most cases, ``<contentOptions>`` will just be a couple of options defining
143 the download method and method-specific details like a commit tag or archive
146 .. code-block:: cmake
148 FetchContent_Declare(
150 GIT_REPOSITORY https://github.com/google/googletest.git
151 GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
154 FetchContent_Declare(
156 URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
157 URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
160 FetchContent_Declare(
161 myCompanyCertificates
162 SVN_REPOSITORY svn+ssh://svn.mycompany.com/srv/svn/trunk/certs
166 Where contents are being fetched from a remote location and you do not
167 control that server, it is advisable to use a hash for ``GIT_TAG`` rather
168 than a branch or tag name. A commit hash is more secure and helps to
169 confirm that the downloaded contents are what you expected.
171 .. versionchanged:: 3.14
172 Commands for the download, update or patch steps can access the terminal.
173 This may be needed for things like password prompts or real-time display
176 .. versionadded:: 3.22
177 The :variable:`CMAKE_TLS_VERIFY`, :variable:`CMAKE_TLS_CAINFO`,
178 :variable:`CMAKE_NETRC` and :variable:`CMAKE_NETRC_FILE` variables now
179 provide the defaults for their corresponding content options, just like
180 they do for :command:`ExternalProject_Add`. Previously, these variables
181 were ignored by the ``FetchContent`` module.
183 .. versionadded:: 3.24
185 ``FIND_PACKAGE_ARGS``
186 This option is for scenarios where the
187 :command:`FetchContent_MakeAvailable` command may first try a call to
188 :command:`find_package` to satisfy the dependency for ``<name>``.
189 By default, such a call would be simply ``find_package(<name>)``, but
190 ``FIND_PACKAGE_ARGS`` can be used to provide additional arguments to be
191 appended after the ``<name>``. ``FIND_PACKAGE_ARGS`` can also be given
192 with nothing after it, which indicates that :command:`find_package` can
193 still be called if :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` is
194 set to ``OPT_IN`` or is not set.
196 Everything after the ``FIND_PACKAGE_ARGS`` keyword is appended to the
197 :command:`find_package` call, so all other ``<contentOptions>`` must
198 come before the ``FIND_PACKAGE_ARGS`` keyword. If the
199 :variable:`CMAKE_FIND_PACKAGE_TARGETS_GLOBAL` variable is set to true
200 at the time ``FetchContent_Declare()`` is called, a ``GLOBAL`` keyword
201 will be appended to the :command:`find_package` arguments if it was
202 not already specified. It will also be appended if
203 ``FIND_PACKAGE_ARGS`` was not given, but
204 :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` was set to ``ALWAYS``.
206 ``OVERRIDE_FIND_PACKAGE`` cannot be used when ``FIND_PACKAGE_ARGS`` is
209 :ref:`dependency_providers` discusses another way that
210 :command:`FetchContent_MakeAvailable` calls can be redirected.
211 ``FIND_PACKAGE_ARGS`` is intended for project control, whereas
212 dependency providers allow users to override project behavior.
214 ``OVERRIDE_FIND_PACKAGE``
215 When a ``FetchContent_Declare(<name> ...)`` call includes this option,
216 subsequent calls to ``find_package(<name> ...)`` will ensure that
217 ``FetchContent_MakeAvailable(<name>)`` has been called, then use the
218 config package files in the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR`
219 directory (which are usually created by ``FetchContent_MakeAvailable()``).
220 This effectively makes :command:`FetchContent_MakeAvailable` override
221 :command:`find_package` for the named dependency, allowing the former to
222 satisfy the package requirements of the latter. ``FIND_PACKAGE_ARGS``
223 cannot be used when ``OVERRIDE_FIND_PACKAGE`` is given.
225 If a :ref:`dependency provider <dependency_providers>` has been set
226 and the project calls :command:`find_package` for the ``<name>``
227 dependency, ``OVERRIDE_FIND_PACKAGE`` will not prevent the provider
228 from seeing that call. Dependency providers always have the opportunity
229 to intercept any direct call to :command:`find_package`, except if that
230 call contains the ``BYPASS_PROVIDER`` option.
232 .. command:: FetchContent_MakeAvailable
234 .. versionadded:: 3.14
236 .. code-block:: cmake
238 FetchContent_MakeAvailable(<name1> [<name2>...])
240 This command ensures that each of the named dependencies are made available
241 to the project by the time it returns. There must have been a call to
242 :command:`FetchContent_Declare` for each dependency, and the first such call
243 will control how that dependency will be made available, as described below.
245 If ``<lowercaseName>_SOURCE_DIR`` is not set:
247 * .. versionadded:: 3.24
249 If a :ref:`dependency provider <dependency_providers>` is set, call the
250 provider's command with ``FETCHCONTENT_MAKEAVAILABLE_SERIAL`` as the
251 first argument, followed by the arguments of the first call to
252 :command:`FetchContent_Declare` for ``<name>``. If ``SOURCE_DIR`` or
253 ``BINARY_DIR`` were not part of the original declared arguments, they
254 will be added with their default values.
255 If :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` was set to ``NEVER``
256 when the details were declared, any ``FIND_PACKAGE_ARGS`` will be
257 omitted. The ``OVERRIDE_FIND_PACKAGE`` keyword is also always omitted.
258 If the provider fulfilled the request, ``FetchContent_MakeAvailable()``
259 will consider that dependency handled, skip the remaining steps below
260 and move on to the next dependency in the list.
262 * .. versionadded:: 3.24
264 If permitted, :command:`find_package(<name> [<args>...]) <find_package>`
265 will be called, where ``<args>...`` may be provided by the
266 ``FIND_PACKAGE_ARGS`` option in :command:`FetchContent_Declare`.
267 The value of the :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` variable
268 at the time :command:`FetchContent_Declare` was called determines whether
269 ``FetchContent_MakeAvailable()`` can call :command:`find_package`.
270 If the :variable:`CMAKE_FIND_PACKAGE_TARGETS_GLOBAL` variable is set to
271 true when ``FetchContent_MakeAvailable()`` is called, it still affects
272 any imported targets created when that in turn calls
273 :command:`find_package`, even if that variable was false when the
274 corresponding details were declared.
276 If the dependency was not satisfied by a provider or a
277 :command:`find_package` call, ``FetchContent_MakeAvailable()`` then uses
278 the following logic to make the dependency available:
280 * If the dependency has already been populated earlier in this run, set
281 the ``<lowercaseName>_POPULATED``, ``<lowercaseName>_SOURCE_DIR`` and
282 ``<lowercaseName>_BINARY_DIR`` variables in the same way as a call to
283 :command:`FetchContent_GetProperties`, then skip the remaining steps
284 below and move on to the next dependency in the list.
286 * Call :command:`FetchContent_Populate` to populate the dependency using
287 the details recorded by an earlier call to :command:`FetchContent_Declare`.
288 Halt with a fatal error if no such details have been recorded.
289 :variable:`FETCHCONTENT_SOURCE_DIR_<uppercaseName>` can be used to override
290 the declared details and use content provided at the specified location
293 * .. versionadded:: 3.24
295 Ensure the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` directory
296 contains a ``<lowercaseName>-config.cmake`` and a
297 ``<lowercaseName>-config-version.cmake`` file (or equivalently
298 ``<name>Config.cmake`` and ``<name>ConfigVersion.cmake``).
299 The directory that the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR`
300 variable points to is cleared at the start of every CMake run.
301 If no config file exists when :command:`FetchContent_Populate` returns,
302 a minimal one will be written which :command:`includes <include>` any
303 ``<lowercaseName>-extra.cmake`` or ``<name>Extra.cmake`` file with the
304 ``OPTIONAL`` flag (so the files can be missing and won't generate a
305 warning). Similarly, if no config version file exists, a very simple
306 one will be written which sets ``PACKAGE_VERSION_COMPATIBLE`` and
307 ``PACKAGE_VERSION_EXACT`` to true. This ensures all future calls to
308 :command:`find_package()` for the dependency will use the redirected
309 config file, regardless of any version requirements.
310 CMake cannot automatically determine an arbitrary dependency's version,
311 so it cannot set ``PACKAGE_VERSION``.
312 When a dependency is pulled in via :command:`add_subdirectory` in the
313 next step, it may choose to overwrite the generated config version file
314 in :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` with one that also sets
316 The dependency may also write a ``<lowercaseName>-extra.cmake`` or
317 ``<name>Extra.cmake`` file to perform custom processing or define any
318 variables that their normal (installed) package config file would
319 otherwise usually define (many projects don't do any custom processing
320 or set any variables and therefore have no need to do this).
321 If required, the main project can write these files instead if the
322 dependency project doesn't do so. This allows the main project to
323 add missing details from older dependencies that haven't or can't be
324 updated to support this functionality.
325 See `Integrating With find_package()`_ for examples.
327 * If the top directory of the populated content contains a ``CMakeLists.txt``
328 file, call :command:`add_subdirectory` to add it to the main build.
329 It is not an error for there to be no ``CMakeLists.txt`` file, which
330 allows the command to be used for dependencies that make downloaded
331 content available at a known location, but which do not need or support
332 being added directly to the build.
334 .. versionadded:: 3.18
335 The ``SOURCE_SUBDIR`` option can be given in the declared details to
336 look somewhere below the top directory instead (i.e. the same way that
337 ``SOURCE_SUBDIR`` is used by the :command:`ExternalProject_Add`
338 command). The path provided with ``SOURCE_SUBDIR`` must be relative
339 and will be treated as relative to the top directory. It can also
340 point to a directory that does not contain a ``CMakeLists.txt`` file
341 or even to a directory that doesn't exist. This can be used to avoid
342 adding a project that contains a ``CMakeLists.txt`` file in its top
345 Projects should aim to declare the details of all dependencies they might
346 use before they call ``FetchContent_MakeAvailable()`` for any of them.
347 This ensures that if any of the dependencies are also sub-dependencies of
348 one or more of the others, the main project still controls the details
349 that will be used (because it will declare them first before the
350 dependencies get a chance to). In the following code samples, assume that
351 the ``uses_other`` dependency also uses ``FetchContent`` to add the ``other``
352 dependency internally:
354 .. code-block:: cmake
356 # WRONG: Should declare all details first
357 FetchContent_Declare(uses_other ...)
358 FetchContent_MakeAvailable(uses_other)
360 FetchContent_Declare(other ...) # Will be ignored, uses_other beat us to it
361 FetchContent_MakeAvailable(other) # Would use details declared by uses_other
363 .. code-block:: cmake
365 # CORRECT: All details declared first, so they will take priority
366 FetchContent_Declare(uses_other ...)
367 FetchContent_Declare(other ...)
368 FetchContent_MakeAvailable(uses_other other)
370 Note that :variable:`CMAKE_VERIFY_INTERFACE_HEADER_SETS` is explicitly set
371 to false upon entry to ``FetchContent_MakeAvailable()``, and is restored to
372 its original value before the command returns. Developers typically only
373 want to verify header sets from the main project, not those from any
374 dependencies. This local manipulation of the
375 :variable:`CMAKE_VERIFY_INTERFACE_HEADER_SETS` variable provides that
376 intuitive behavior. You can use variables like
377 :variable:`CMAKE_PROJECT_INCLUDE` or
378 :variable:`CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE` to turn verification back
379 on for all or some dependencies. You can also set the
380 :prop_tgt:`VERIFY_INTERFACE_HEADER_SETS` property of individual targets.
382 .. command:: FetchContent_Populate
385 Where possible, prefer to use :command:`FetchContent_MakeAvailable`
386 instead of implementing population manually with this command.
388 .. code-block:: cmake
390 FetchContent_Populate(<name>)
392 In most cases, the only argument given to ``FetchContent_Populate()`` is the
393 ``<name>``. When used this way, the command assumes the content details have
394 been recorded by an earlier call to :command:`FetchContent_Declare`. The
395 details are stored in a global property, so they are unaffected by things
396 like variable or directory scope. Therefore, it doesn't matter where in the
397 project the details were previously declared, as long as they have been
398 declared before the call to ``FetchContent_Populate()``. Those saved details
399 are then used to construct a call to :command:`ExternalProject_Add` in a
400 private sub-build to perform the content population immediately. The
401 implementation of ``ExternalProject_Add()`` ensures that if the content has
402 already been populated in a previous CMake run, that content will be reused
403 rather than repopulating them again. For the common case where population
404 involves downloading content, the cost of the download is only paid once.
406 An internal global property records when a particular content population
407 request has been processed. If ``FetchContent_Populate()`` is called more
408 than once for the same content name within a configure run, the second call
409 will halt with an error. Projects can and should check whether content
410 population has already been processed with the
411 :command:`FetchContent_GetProperties` command before calling
412 ``FetchContent_Populate()``.
414 ``FetchContent_Populate()`` will set three variables in the scope of the
417 ``<lowercaseName>_POPULATED``
418 This will always be set to ``TRUE`` by the call.
420 ``<lowercaseName>_SOURCE_DIR``
421 The location where the populated content can be found upon return.
423 ``<lowercaseName>_BINARY_DIR``
424 A directory intended for use as a corresponding build directory.
426 The main use case for the ``<lowercaseName>_SOURCE_DIR`` and
427 ``<lowercaseName>_BINARY_DIR`` variables is to call
428 :command:`add_subdirectory` immediately after population:
430 .. code-block:: cmake
432 FetchContent_Populate(FooBar)
433 add_subdirectory(${foobar_SOURCE_DIR} ${foobar_BINARY_DIR})
435 The values of the three variables can also be retrieved from anywhere in the
436 project hierarchy using the :command:`FetchContent_GetProperties` command.
438 The ``FetchContent_Populate()`` command also supports a syntax allowing the
439 content details to be specified directly rather than using any saved
440 details. This is more low-level and use of this form is generally to be
441 avoided in favor of using saved content details as outlined above.
442 Nevertheless, in certain situations it can be useful to invoke the content
443 population as an isolated operation (typically as part of implementing some
444 other higher level feature or when using CMake in script mode):
446 .. code-block:: cmake
448 FetchContent_Populate(
451 [SUBBUILD_DIR <subBuildDir>]
452 [SOURCE_DIR <srcDir>]
453 [BINARY_DIR <binDir>]
457 This form has a number of key differences to that where only ``<name>`` is
460 - All required population details are assumed to have been provided directly
461 in the call to ``FetchContent_Populate()``. Any saved details for
462 ``<name>`` are ignored.
463 - No check is made for whether content for ``<name>`` has already been
465 - No global property is set to record that the population has occurred.
466 - No global properties record the source or binary directories used for the
468 - The ``FETCHCONTENT_FULLY_DISCONNECTED`` and
469 ``FETCHCONTENT_UPDATES_DISCONNECTED`` cache variables are ignored.
471 The ``<lowercaseName>_SOURCE_DIR`` and ``<lowercaseName>_BINARY_DIR``
472 variables are still returned to the caller, but since these locations are
473 not stored as global properties when this form is used, they are only
474 available to the calling scope and below rather than the entire project
475 hierarchy. No ``<lowercaseName>_POPULATED`` variable is set in the caller's
476 scope with this form.
478 The supported options for ``FetchContent_Populate()`` are the same as those
479 for :command:`FetchContent_Declare()`. Those few options shown just
480 above are either specific to ``FetchContent_Populate()`` or their behavior is
481 slightly modified from how :command:`ExternalProject_Add` treats them:
484 The ``QUIET`` option can be given to hide the output associated with
485 populating the specified content. If the population fails, the output will
486 be shown regardless of whether this option was given or not so that the
487 cause of the failure can be diagnosed. The global ``FETCHCONTENT_QUIET``
488 cache variable has no effect on ``FetchContent_Populate()`` calls where the
489 content details are provided directly.
492 The ``SUBBUILD_DIR`` argument can be provided to change the location of the
493 sub-build created to perform the population. The default value is
494 ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-subbuild`` and it would be
495 unusual to need to override this default. If a relative path is specified,
496 it will be interpreted as relative to :variable:`CMAKE_CURRENT_BINARY_DIR`.
497 This option should not be confused with the ``SOURCE_SUBDIR`` option which
498 only affects the :command:`FetchContent_MakeAvailable` command.
500 ``SOURCE_DIR``, ``BINARY_DIR``
501 The ``SOURCE_DIR`` and ``BINARY_DIR`` arguments are supported by
502 :command:`ExternalProject_Add`, but different default values are used by
503 ``FetchContent_Populate()``. ``SOURCE_DIR`` defaults to
504 ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-src`` and ``BINARY_DIR``
505 defaults to ``${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-build``.
506 If a relative path is specified, it will be interpreted as relative to
507 :variable:`CMAKE_CURRENT_BINARY_DIR`.
509 In addition to the above explicit options, any other unrecognized options are
510 passed through unmodified to :command:`ExternalProject_Add` to perform the
511 download, patch and update steps. The following options are explicitly
512 prohibited (they are disabled by the ``FetchContent_Populate()`` command):
514 - ``CONFIGURE_COMMAND``
516 - ``INSTALL_COMMAND``
519 If using ``FetchContent_Populate()`` within CMake's script mode, be aware
520 that the implementation sets up a sub-build which therefore requires a CMake
521 generator and build tool to be available. If these cannot be found by
522 default, then the :variable:`CMAKE_GENERATOR` and/or
523 :variable:`CMAKE_MAKE_PROGRAM` variables will need to be set appropriately
524 on the command line invoking the script.
526 .. versionadded:: 3.18
527 Added support for the ``DOWNLOAD_NO_EXTRACT`` option.
529 .. command:: FetchContent_GetProperties
531 When using saved content details, a call to
532 :command:`FetchContent_MakeAvailable` or :command:`FetchContent_Populate`
533 records information in global properties which can be queried at any time.
534 This information may include the source and binary directories associated with
535 the content and also whether or not the content population has been processed
536 during the current configure run.
538 .. code-block:: cmake
540 FetchContent_GetProperties(
542 [SOURCE_DIR <srcDirVar>]
543 [BINARY_DIR <binDirVar>]
544 [POPULATED <doneVar>]
547 The ``SOURCE_DIR``, ``BINARY_DIR`` and ``POPULATED`` options can be used to
548 specify which properties should be retrieved. Each option accepts a value
549 which is the name of the variable in which to store that property. Most of
550 the time though, only ``<name>`` is given, in which case the call will then
551 set the same variables as a call to
552 :command:`FetchContent_MakeAvailable(name) <FetchContent_MakeAvailable>` or
553 :command:`FetchContent_Populate(name) <FetchContent_Populate>`.
554 Note that the ``SOURCE_DIR`` and ``BINARY_DIR`` values can be empty if the
555 call is fulfilled by a :ref:`dependency provider <dependency_providers>`.
557 This command is rarely needed when using
558 :command:`FetchContent_MakeAvailable`. It is more commonly used as part of
559 implementing the following pattern with :command:`FetchContent_Populate`,
560 which ensures that the relevant variables will always be defined regardless
561 of whether or not the population has been performed elsewhere in the project
564 .. code-block:: cmake
566 # Check if population has already been performed
567 FetchContent_GetProperties(depname)
568 if(NOT depname_POPULATED)
569 # Fetch the content using previously declared details
570 FetchContent_Populate(depname)
572 # Set custom variables, policies, etc.
575 # Bring the populated content into the build
576 add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR})
579 .. command:: FetchContent_SetPopulated
581 .. versionadded:: 3.24
584 This command should only be called by
585 :ref:`dependency providers <dependency_providers>`. Calling it in any
586 other context is unsupported and future CMake versions may halt with a
587 fatal error in such cases.
589 .. code-block:: cmake
591 FetchContent_SetPopulated(
593 [SOURCE_DIR <srcDir>]
594 [BINARY_DIR <binDir>]
597 If a provider command fulfills a ``FETCHCONTENT_MAKEAVAILABLE_SERIAL``
598 request, it must call this function before returning. The ``SOURCE_DIR``
599 and ``BINARY_DIR`` arguments can be used to specify the values that
600 :command:`FetchContent_GetProperties` should return for its corresponding
601 arguments. Only provide ``SOURCE_DIR`` and ``BINARY_DIR`` if they have
602 the same meaning as if they had been populated by the built-in
603 :command:`FetchContent_MakeAvailable` implementation.
609 A number of cache variables can influence the behavior where details from a
610 :command:`FetchContent_Declare` call are used to populate content.
613 All of these variables are intended for the developer to customize behavior.
614 They should not normally be set by the project.
616 .. variable:: FETCHCONTENT_BASE_DIR
618 In most cases, the saved details do not specify any options relating to the
619 directories to use for the internal sub-build, final source and build areas.
620 It is generally best to leave these decisions up to the ``FetchContent``
621 module to handle on the project's behalf. The ``FETCHCONTENT_BASE_DIR``
622 cache variable controls the point under which all content population
623 directories are collected, but in most cases, developers would not need to
624 change this. The default location is ``${CMAKE_BINARY_DIR}/_deps``, but if
625 developers change this value, they should aim to keep the path short and
626 just below the top level of the build tree to avoid running into path
627 length problems on Windows.
629 .. variable:: FETCHCONTENT_QUIET
631 The logging output during population can be quite verbose, making the
632 configure stage quite noisy. This cache option (``ON`` by default) hides
633 all population output unless an error is encountered. If experiencing
634 problems with hung downloads, temporarily switching this option off may
635 help diagnose which content population is causing the issue.
637 .. variable:: FETCHCONTENT_FULLY_DISCONNECTED
639 When this option is enabled, no attempt is made to download or update
640 any content. It is assumed that all content has already been populated in
641 a previous run or the source directories have been pointed at existing
642 contents the developer has provided manually (using options described
643 further below). When the developer knows that no changes have been made to
644 any content details, turning this option ``ON`` can significantly speed up
645 the configure stage. It is ``OFF`` by default.
647 .. variable:: FETCHCONTENT_UPDATES_DISCONNECTED
649 This is a less severe download/update control compared to
650 :variable:`FETCHCONTENT_FULLY_DISCONNECTED`. Instead of bypassing all
651 download and update logic, ``FETCHCONTENT_UPDATES_DISCONNECTED`` only
652 disables the update stage. Therefore, if content has not been downloaded
653 previously, it will still be downloaded when this option is enabled.
654 This can speed up the configure stage, but not as much as
655 :variable:`FETCHCONTENT_FULLY_DISCONNECTED`. It is ``OFF`` by default.
657 .. variable:: FETCHCONTENT_TRY_FIND_PACKAGE_MODE
659 .. versionadded:: 3.24
661 This variable modifies the details that :command:`FetchContent_Declare`
662 records for a given dependency. While it ultimately controls the behavior
663 of :command:`FetchContent_MakeAvailable`, it is the variable's value when
664 :command:`FetchContent_Declare` is called that gets used. It makes no
665 difference what the variable is set to when
666 :command:`FetchContent_MakeAvailable` is called. Since the variable should
667 only be set by the user and not by projects directly, it will typically have
668 the same value throughout anyway, so this distinction is not usually
671 ``FETCHCONTENT_TRY_FIND_PACKAGE_MODE`` ultimately controls whether
672 :command:`FetchContent_MakeAvailable` is allowed to call
673 :command:`find_package` to satisfy a dependency. The variable can be set
674 to one of the following values:
677 :command:`FetchContent_MakeAvailable` will only call
678 :command:`find_package` if the :command:`FetchContent_Declare` call
679 included a ``FIND_PACKAGE_ARGS`` keyword. This is also the default
680 behavior if ``FETCHCONTENT_TRY_FIND_PACKAGE_MODE`` is not set.
683 :command:`find_package` can be called by
684 :command:`FetchContent_MakeAvailable` regardless of whether the
685 :command:`FetchContent_Declare` call included a ``FIND_PACKAGE_ARGS``
686 keyword or not. If no ``FIND_PACKAGE_ARGS`` keyword was given, the
687 behavior will be as though ``FIND_PACKAGE_ARGS`` had been provided,
688 with no additional arguments after it.
691 :command:`FetchContent_MakeAvailable` will not call
692 :command:`find_package`. Any ``FIND_PACKAGE_ARGS`` given to the
693 :command:`FetchContent_Declare` call will be ignored.
695 As a special case, if the :variable:`FETCHCONTENT_SOURCE_DIR_<uppercaseName>`
696 variable has a non-empty value for a dependency, it is assumed that the
697 user is overriding all other methods of making that dependency available.
698 ``FETCHCONTENT_TRY_FIND_PACKAGE_MODE`` will have no effect on that
699 dependency and :command:`FetchContent_MakeAvailable` will not try to call
700 :command:`find_package` for it.
702 In addition to the above, the following variables are also defined for each
705 .. variable:: FETCHCONTENT_SOURCE_DIR_<uppercaseName>
707 If this is set, no download or update steps are performed for the specified
708 content and the ``<lowercaseName>_SOURCE_DIR`` variable returned to the
709 caller is pointed at this location. This gives developers a way to have a
710 separate checkout of the content that they can modify freely without
711 interference from the build. The build simply uses that existing source,
712 but it still defines ``<lowercaseName>_BINARY_DIR`` to point inside its own
713 build area. Developers are strongly encouraged to use this mechanism rather
714 than editing the sources populated in the default location, as changes to
715 sources in the default location can be lost when content population details
716 are changed by the project.
718 .. variable:: FETCHCONTENT_UPDATES_DISCONNECTED_<uppercaseName>
720 This is the per-content equivalent of
721 :variable:`FETCHCONTENT_UPDATES_DISCONNECTED`. If the global option or
722 this option is ``ON``, then updates will be disabled for the named content.
723 Disabling updates for individual content can be useful for content whose
724 details rarely change, while still leaving other frequently changing content
725 with updates enabled.
727 .. _`fetch-content-examples`:
735 This first fairly straightforward example ensures that some popular testing
736 frameworks are available to the main build:
738 .. code-block:: cmake
740 include(FetchContent)
741 FetchContent_Declare(
743 GIT_REPOSITORY https://github.com/google/googletest.git
744 GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
746 FetchContent_Declare(
748 GIT_REPOSITORY https://github.com/catchorg/Catch2.git
749 GIT_TAG de6fe184a9ac1a06895cdd1c9b437f0a0bdf14ad # v2.13.4
752 # After the following call, the CMake targets defined by googletest and
753 # Catch2 will be available to the rest of the build
754 FetchContent_MakeAvailable(googletest Catch2)
756 .. _FetchContent-find_package-integration-examples:
758 Integrating With find_package()
759 """""""""""""""""""""""""""""""
761 For the previous example, if the user wanted to try to find ``googletest``
762 and ``Catch2`` via :command:`find_package` first before trying to download
763 and build them from source, they could set the
764 :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` variable to ``ALWAYS``.
765 This would also affect any other calls to :command:`FetchContent_Declare`
766 throughout the project, which might not be acceptable. The behavior can be
767 enabled for just these two dependencies instead by adding ``FIND_PACKAGE_ARGS``
768 to the declared details and leaving
769 :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` unset, or set to ``OPT_IN``:
771 .. code-block:: cmake
773 include(FetchContent)
774 FetchContent_Declare(
776 GIT_REPOSITORY https://github.com/google/googletest.git
777 GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
778 FIND_PACKAGE_ARGS NAMES GTest
780 FetchContent_Declare(
782 GIT_REPOSITORY https://github.com/catchorg/Catch2.git
783 GIT_TAG de6fe184a9ac1a06895cdd1c9b437f0a0bdf14ad # v2.13.4
787 # This will try calling find_package() first for both dependencies
788 FetchContent_MakeAvailable(googletest Catch2)
790 For ``Catch2``, no additional arguments to :command:`find_package` are needed,
791 so no additional arguments are provided after the ``FIND_PACKAGE_ARGS``
792 keyword. For ``googletest``, its package is more commonly called ``GTest``,
793 so arguments are added to support it being found by that name.
795 If the user wanted to disable :command:`FetchContent_MakeAvailable` from
796 calling :command:`find_package` for any dependency, even if it provided
797 ``FIND_PACKAGE_ARGS`` in its declared details, they could set
798 :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` to ``NEVER``.
800 If the project wanted to indicate that these two dependencies should be
801 downloaded and built from source and that :command:`find_package` calls
802 should be redirected to use the built dependencies, the
803 ``OVERRIDE_FIND_PACKAGE`` option should be used when declaring the content
806 .. code-block:: cmake
808 include(FetchContent)
809 FetchContent_Declare(
811 GIT_REPOSITORY https://github.com/google/googletest.git
812 GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
813 OVERRIDE_FIND_PACKAGE
815 FetchContent_Declare(
817 GIT_REPOSITORY https://github.com/catchorg/Catch2.git
818 GIT_TAG de6fe184a9ac1a06895cdd1c9b437f0a0bdf14ad # v2.13.4
819 OVERRIDE_FIND_PACKAGE
822 # The following will automatically forward through to FetchContent_MakeAvailable()
823 find_package(googletest)
826 CMake provides a FindGTest module which defines some variables that older
827 projects may use instead of linking to the imported targets. To support
828 those cases, we can provide an extra file. In keeping with the
829 "first to define, wins" philosophy of ``FetchContent``, we only write out
830 that file if something else hasn't already done so.
832 .. code-block:: cmake
834 FetchContent_MakeAvailable(googletest)
836 if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-extra.cmake AND
837 NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletestExtra.cmake)
838 file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-extra.cmake
840 if("${GTEST_LIBRARIES}" STREQUAL "" AND TARGET GTest::gtest)
841 set(GTEST_LIBRARIES GTest::gtest)
843 if("${GTEST_MAIN_LIBRARIES}" STREQUAL "" AND TARGET GTest::gtest_main)
844 set(GTEST_MAIN_LIBRARIES GTest::gtest_main)
846 if("${GTEST_BOTH_LIBRARIES}" STREQUAL "")
847 set(GTEST_BOTH_LIBRARIES ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES})
852 Projects will also likely be using ``find_package(GTest)`` rather than
853 ``find_package(googletest)``, but it is possible to make use of the
854 :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` area to pull in the latter as
855 a dependency of the former. This is likely to be sufficient to satisfy
856 a typical ``find_package(GTest)`` call.
858 .. code-block:: cmake
860 FetchContent_MakeAvailable(googletest)
862 if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake AND
863 NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfig.cmake)
864 file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake
866 include(CMakeFindDependencyMacro)
867 find_dependency(googletest)
871 if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config-version.cmake AND
872 NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfigVersion.cmake)
873 file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config-version.cmake
875 include(${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-config-version.cmake OPTIONAL)
876 if(NOT PACKAGE_VERSION_COMPATIBLE)
877 include(${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletestConfigVersion.cmake OPTIONAL)
882 Overriding Where To Find CMakeLists.txt
883 """""""""""""""""""""""""""""""""""""""
885 If the sub-project's ``CMakeLists.txt`` file is not at the top level of its
886 source tree, the ``SOURCE_SUBDIR`` option can be used to tell ``FetchContent``
887 where to find it. The following example shows how to use that option and
888 it also sets a variable which is meaningful to the subproject before pulling
889 it into the main build:
891 .. code-block:: cmake
893 include(FetchContent)
894 FetchContent_Declare(
896 GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git
897 GIT_TAG ae50d9b9902526efd6c7a1907d09739f959c6297 # v3.15.0
900 set(protobuf_BUILD_TESTS OFF)
901 FetchContent_MakeAvailable(protobuf)
903 Complex Dependency Hierarchies
904 """"""""""""""""""""""""""""""
906 In more complex project hierarchies, the dependency relationships can be more
907 complicated. Consider a hierarchy where ``projA`` is the top level project and
908 it depends directly on projects ``projB`` and ``projC``. Both ``projB`` and
909 ``projC`` can be built standalone and they also both depend on another project
910 ``projD``. ``projB`` additionally depends on ``projE``. This example assumes
911 that all five projects are available on a company git server. The
912 ``CMakeLists.txt`` of each project might have sections like the following:
916 .. code-block:: cmake
918 include(FetchContent)
919 FetchContent_Declare(
921 GIT_REPOSITORY git@mycompany.com:git/projB.git
922 GIT_TAG 4a89dc7e24ff212a7b5167bef7ab079d
924 FetchContent_Declare(
926 GIT_REPOSITORY git@mycompany.com:git/projC.git
927 GIT_TAG 4ad4016bd1d8d5412d135cf8ceea1bb9
929 FetchContent_Declare(
931 GIT_REPOSITORY git@mycompany.com:git/projD.git
932 GIT_TAG origin/integrationBranch
934 FetchContent_Declare(
936 GIT_REPOSITORY git@mycompany.com:git/projE.git
940 # Order is important, see notes in the discussion further below
941 FetchContent_MakeAvailable(projD projB projC)
945 .. code-block:: cmake
947 include(FetchContent)
948 FetchContent_Declare(
950 GIT_REPOSITORY git@mycompany.com:git/projD.git
951 GIT_TAG 20b415f9034bbd2a2e8216e9a5c9e632
953 FetchContent_Declare(
955 GIT_REPOSITORY git@mycompany.com:git/projE.git
956 GIT_TAG 68e20f674a48be38d60e129f600faf7d
959 FetchContent_MakeAvailable(projD projE)
963 .. code-block:: cmake
965 include(FetchContent)
966 FetchContent_Declare(
968 GIT_REPOSITORY git@mycompany.com:git/projD.git
969 GIT_TAG 7d9a17ad2c962aa13e2fbb8043fb6b8a
972 # This particular version of projD requires workarounds
973 FetchContent_GetProperties(projD)
974 if(NOT projd_POPULATED)
975 FetchContent_Populate(projD)
977 # Copy an additional/replacement file into the populated source
978 file(COPY someFile.c DESTINATION ${projd_SOURCE_DIR}/src)
980 add_subdirectory(${projd_SOURCE_DIR} ${projd_BINARY_DIR})
983 A few key points should be noted in the above:
985 - ``projB`` and ``projC`` define different content details for ``projD``,
986 but ``projA`` also defines a set of content details for ``projD``.
987 Because ``projA`` will define them first, the details from ``projB`` and
988 ``projC`` will not be used. The override details defined by ``projA``
989 are not required to match either of those from ``projB`` or ``projC``, but
990 it is up to the higher level project to ensure that the details it does
991 define still make sense for the child projects.
992 - In the ``projA`` call to :command:`FetchContent_MakeAvailable`, ``projD``
993 is listed ahead of ``projB`` and ``projC`` to ensure that ``projA`` is in
994 control of how ``projD`` is populated.
995 - While ``projA`` defines content details for ``projE``, it does not need
996 to explicitly call ``FetchContent_MakeAvailable(projE)`` or
997 ``FetchContent_Populate(projD)`` itself. Instead, it leaves that to the
998 child ``projB``. For higher level projects, it is often enough to just
999 define the override content details and leave the actual population to the
1000 child projects. This saves repeating the same thing at each level of the
1001 project hierarchy unnecessarily.
1003 Populating Content Without Adding It To The Build
1004 """""""""""""""""""""""""""""""""""""""""""""""""
1006 Projects don't always need to add the populated content to the build.
1007 Sometimes the project just wants to make the downloaded content available at
1008 a predictable location. The next example ensures that a set of standard
1009 company toolchain files (and potentially even the toolchain binaries
1010 themselves) is available early enough to be used for that same build.
1012 .. code-block:: cmake
1014 cmake_minimum_required(VERSION 3.14)
1016 include(FetchContent)
1017 FetchContent_Declare(
1019 URL https://intranet.mycompany.com//toolchains_1.3.2.tar.gz
1021 FetchContent_MakeAvailable(mycom_toolchains)
1023 project(CrossCompileExample)
1025 The project could be configured to use one of the downloaded toolchains like
1028 .. code-block:: shell
1030 cmake -DCMAKE_TOOLCHAIN_FILE=_deps/mycom_toolchains-src/toolchain_arm.cmake /path/to/src
1032 When CMake processes the ``CMakeLists.txt`` file, it will download and unpack
1033 the tarball into ``_deps/mycompany_toolchains-src`` relative to the build
1034 directory. The :variable:`CMAKE_TOOLCHAIN_FILE` variable is not used until
1035 the :command:`project` command is reached, at which point CMake looks for the
1036 named toolchain file relative to the build directory. Because the tarball has
1037 already been downloaded and unpacked by then, the toolchain file will be in
1038 place, even the very first time that ``cmake`` is run in the build directory.
1040 Populating Content In CMake Script Mode
1041 """""""""""""""""""""""""""""""""""""""
1043 This last example demonstrates how one might download and unpack a
1044 firmware tarball using CMake's :manual:`script mode <cmake(1)>`. The call to
1045 :command:`FetchContent_Populate` specifies all the content details and the
1046 unpacked firmware will be placed in a ``firmware`` directory below the
1047 current working directory.
1049 *getFirmware.cmake*:
1051 .. code-block:: cmake
1053 # NOTE: Intended to be run in script mode with cmake -P
1054 include(FetchContent)
1055 FetchContent_Populate(
1057 URL https://mycompany.com/assets/firmware-1.23-arm.tar.gz
1058 URL_HASH MD5=68247684da89b608d466253762b0ff11
1062 #]=======================================================================]
1064 #=======================================================================
1065 # Recording and retrieving content details for later population
1066 #=======================================================================
1068 # Internal use, projects must not call this directly. It is
1069 # intended for use by FetchContent_Declare() only.
1071 # Sets a content-specific global property (not meant for use
1072 # outside of functions defined here in this file) which can later
1073 # be retrieved using __FetchContent_getSavedDetails() with just the
1074 # same content name. If there is already a value stored in the
1075 # property, it is left unchanged and this call has no effect.
1076 # This allows parent projects to define the content details,
1077 # overriding anything a child project may try to set (properties
1078 # are not cached between runs, so the first thing to set it in a
1079 # build will be in control).
1080 function(__FetchContent_declareDetails contentName)
1082 string(TOLOWER ${contentName} contentNameLower)
1083 set(savedDetailsPropertyName "_FetchContent_${contentNameLower}_savedDetails")
1084 get_property(alreadyDefined GLOBAL PROPERTY ${savedDetailsPropertyName} DEFINED)
1089 if("${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}" STREQUAL "ALWAYS")
1090 set(__tryFindPackage TRUE)
1091 set(__tryFindPackageAllowed TRUE)
1092 elseif("${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}" STREQUAL "NEVER")
1093 set(__tryFindPackage FALSE)
1094 set(__tryFindPackageAllowed FALSE)
1095 elseif("${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}" STREQUAL "OPT_IN" OR
1096 NOT DEFINED FETCHCONTENT_TRY_FIND_PACKAGE_MODE)
1097 set(__tryFindPackage FALSE)
1098 set(__tryFindPackageAllowed TRUE)
1101 "Unsupported value for FETCHCONTENT_TRY_FIND_PACKAGE_MODE: "
1102 "${FETCHCONTENT_TRY_FIND_PACKAGE_MODE}"
1107 set(__findPackageArgs)
1108 set(__sawQuietKeyword NO)
1109 set(__sawGlobalKeyword NO)
1110 foreach(__item IN LISTS ARGN)
1111 if(DEFINED __findPackageArgs)
1112 # All remaining args are for find_package()
1113 string(APPEND __findPackageArgs " [==[${__item}]==]")
1114 if(__item STREQUAL "QUIET")
1115 set(__sawQuietKeyword YES)
1116 elseif(__item STREQUAL "GLOBAL")
1117 set(__sawGlobalKeyword YES)
1122 # Still processing non-find_package() args
1123 if(__item STREQUAL "FIND_PACKAGE_ARGS")
1124 if(__tryFindPackageAllowed)
1125 set(__tryFindPackage TRUE)
1127 # All arguments after this keyword are for find_package(). Define the
1128 # variable but with an empty value initially. This allows us to check
1129 # at the start of the loop whether to store remaining items in this
1130 # variable or not. Note that there could be no more args, which is still
1131 # a valid case because we automatically provide ${contentName} as the
1132 # package name and there may not need to be any further arguments.
1133 set(__findPackageArgs "")
1134 continue() # Don't store this item
1135 elseif(__item STREQUAL "OVERRIDE_FIND_PACKAGE")
1136 set(__tryFindPackageAllowed FALSE)
1137 # Define a separate dedicated property for find_package() to check
1138 # in its implementation. This will be a placeholder until FetchContent
1139 # actually does the population. After that, we will have created a
1140 # stand-in config file that find_package() will pick up instead.
1141 set(propertyName "_FetchContent_${contentNameLower}_override_find_package")
1142 define_property(GLOBAL PROPERTY ${propertyName})
1143 set_property(GLOBAL PROPERTY ${propertyName} TRUE)
1146 string(APPEND __cmdArgs " [==[${__item}]==]")
1149 define_property(GLOBAL PROPERTY ${savedDetailsPropertyName})
1150 cmake_language(EVAL CODE
1151 "set_property(GLOBAL PROPERTY ${savedDetailsPropertyName} ${__cmdArgs})"
1154 if(__tryFindPackage AND __tryFindPackageAllowed)
1155 set(propertyName "_FetchContent_${contentNameLower}_find_package_args")
1156 define_property(GLOBAL PROPERTY ${propertyName})
1157 if(NOT __sawQuietKeyword)
1158 list(INSERT __findPackageArgs 0 QUIET)
1160 if(CMAKE_FIND_PACKAGE_TARGETS_GLOBAL AND NOT __sawGlobalKeyword)
1161 list(APPEND __findPackageArgs GLOBAL)
1163 cmake_language(EVAL CODE
1164 "set_property(GLOBAL PROPERTY ${propertyName} ${__findPackageArgs})"
1171 # Internal use, projects must not call this directly. It is
1172 # intended for use by the FetchContent_Declare() function.
1174 # Retrieves details saved for the specified content in an
1175 # earlier call to __FetchContent_declareDetails().
1176 function(__FetchContent_getSavedDetails contentName outVar)
1178 string(TOLOWER ${contentName} contentNameLower)
1179 set(propertyName "_FetchContent_${contentNameLower}_savedDetails")
1180 get_property(alreadyDefined GLOBAL PROPERTY ${propertyName} DEFINED)
1181 if(NOT alreadyDefined)
1182 message(FATAL_ERROR "No content details recorded for ${contentName}")
1184 get_property(propertyValue GLOBAL PROPERTY ${propertyName})
1185 set(${outVar} "${propertyValue}" PARENT_SCOPE)
1190 # Saves population details of the content, sets defaults for the
1191 # SOURCE_DIR and BUILD_DIR.
1192 function(FetchContent_Declare contentName)
1194 # Always check this even if we won't save these details.
1195 # This helps projects catch errors earlier.
1196 # Avoid using if(... IN_LIST ...) so we don't have to alter policy settings
1197 list(FIND ARGN OVERRIDE_FIND_PACKAGE index_OVERRIDE_FIND_PACKAGE)
1198 list(FIND ARGN FIND_PACKAGE_ARGS index_FIND_PACKAGE_ARGS)
1199 if(index_OVERRIDE_FIND_PACKAGE GREATER_EQUAL 0 AND
1200 index_FIND_PACKAGE_ARGS GREATER_EQUAL 0)
1202 "Cannot specify both OVERRIDE_FIND_PACKAGE and FIND_PACKAGE_ARGS "
1203 "when declaring details for ${contentName}"
1207 # Because we are only looking for a subset of the supported keywords, we
1208 # cannot check for multi-value arguments with this method. We will have to
1209 # handle the URL keyword differently.
1213 DOWNLOAD_EXTRACT_TIMESTAMP
1218 cmake_parse_arguments(PARSE_ARGV 1 ARG "" "${oneValueArgs}" "")
1220 string(TOLOWER ${contentName} contentNameLower)
1222 if(NOT ARG_BINARY_DIR)
1223 set(ARG_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
1226 if(NOT ARG_SOURCE_DIR)
1227 set(ARG_SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src")
1230 if(ARG_SVN_REPOSITORY)
1231 # Add a hash of the svn repository URL to the source dir. This works
1232 # around the problem where if the URL changes, the download would
1233 # fail because it tries to checkout/update rather than switch the
1234 # old URL to the new one. We limit the hash to the first 7 characters
1235 # so that the source path doesn't get overly long (which can be a
1236 # problem on windows due to path length limits).
1237 string(SHA1 urlSHA ${ARG_SVN_REPOSITORY})
1238 string(SUBSTRING ${urlSHA} 0 7 urlSHA)
1239 string(APPEND ARG_SOURCE_DIR "-${urlSHA}")
1242 # The ExternalProject_Add() call in the sub-build won't see the CMP0135
1243 # policy setting of our caller. Work out if that policy will be needed and
1244 # explicitly set the relevant option if not already provided. The condition
1245 # here is essentially an abbreviated version of the logic in
1246 # ExternalProject's _ep_add_download_command() function.
1247 if(NOT ARG_DOWNLOAD_NO_EXTRACT AND
1248 NOT DEFINED ARG_DOWNLOAD_EXTRACT_TIMESTAMP)
1249 list(FIND ARGN URL urlIndex)
1250 if(urlIndex GREATER_EQUAL 0)
1251 math(EXPR urlIndex "${urlIndex} + 1")
1252 list(LENGTH ARGN numArgs)
1253 if(urlIndex GREATER_EQUAL numArgs)
1255 "URL keyword needs to be followed by at least one URL"
1258 # If we have multiple URLs, none of them are allowed to be local paths.
1259 # Therefore, we can test just the first URL, and if it is non-local, so
1260 # will be the others if there are more.
1261 list(GET ARGN ${urlIndex} firstUrl)
1262 if(NOT IS_DIRECTORY "${firstUrl}")
1263 cmake_policy(GET CMP0135 _FETCHCONTENT_CMP0135
1264 PARENT_SCOPE # undocumented, do not use outside of CMake
1266 if(_FETCHCONTENT_CMP0135 STREQUAL "")
1267 message(AUTHOR_WARNING
1268 "The DOWNLOAD_EXTRACT_TIMESTAMP option was not given and policy "
1269 "CMP0135 is not set. The policy's OLD behavior will be used. "
1270 "When using a URL download, the timestamps of extracted files "
1271 "should preferably be that of the time of extraction, otherwise "
1272 "code that depends on the extracted contents might not be "
1273 "rebuilt if the URL changes. The OLD behavior preserves the "
1274 "timestamps from the archive instead, but this is usually not "
1275 "what you want. Update your project to the NEW behavior or "
1276 "specify the DOWNLOAD_EXTRACT_TIMESTAMP option with a value of "
1277 "true to avoid this robustness issue."
1279 set(ARG_DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
1280 elseif(_FETCHCONTENT_CMP0135 STREQUAL "NEW")
1281 set(ARG_DOWNLOAD_EXTRACT_TIMESTAMP FALSE)
1283 set(ARG_DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
1289 # Add back in the keyword args we pulled out and potentially tweaked/added
1290 foreach(key IN LISTS oneValueArgs)
1291 if(DEFINED ARG_${key})
1292 list(PREPEND ARG_UNPARSED_ARGUMENTS ${key} "${ARG_${key}}")
1297 foreach(__item IN LISTS ARG_UNPARSED_ARGUMENTS)
1298 string(APPEND __argsQuoted " [==[${__item}]==]")
1300 cmake_language(EVAL CODE
1301 "__FetchContent_declareDetails(${contentNameLower} ${__argsQuoted})"
1307 #=======================================================================
1308 # Set/get whether the specified content has been populated yet.
1309 # The setter also records the source and binary dirs used.
1310 #=======================================================================
1312 # Semi-internal use. Projects must not call this directly. Dependency
1313 # providers must call it if they satisfy a request made with the
1314 # FETCHCONTENT_MAKEAVAILABLE_SERIAL method (that is the only permitted
1315 # place to call it outside of the FetchContent module).
1316 function(FetchContent_SetPopulated contentName)
1318 cmake_parse_arguments(PARSE_ARGV 1 arg
1320 "SOURCE_DIR;BINARY_DIR"
1323 if(NOT "${arg_UNPARSED_ARGUMENTS}" STREQUAL "")
1324 message(FATAL_ERROR "Unsupported arguments: ${arg_UNPARSED_ARGUMENTS}")
1327 string(TOLOWER ${contentName} contentNameLower)
1328 set(prefix "_FetchContent_${contentNameLower}")
1330 set(propertyName "${prefix}_sourceDir")
1331 define_property(GLOBAL PROPERTY ${propertyName})
1332 if("${arg_SOURCE_DIR}" STREQUAL "")
1333 # Don't discard a previously provided SOURCE_DIR
1334 get_property(arg_SOURCE_DIR GLOBAL PROPERTY ${propertyName})
1336 set_property(GLOBAL PROPERTY ${propertyName} "${arg_SOURCE_DIR}")
1338 set(propertyName "${prefix}_binaryDir")
1339 define_property(GLOBAL PROPERTY ${propertyName})
1340 if("${arg_BINARY_DIR}" STREQUAL "")
1341 # Don't discard a previously provided BINARY_DIR
1342 get_property(arg_BINARY_DIR GLOBAL PROPERTY ${propertyName})
1344 set_property(GLOBAL PROPERTY ${propertyName} "${arg_BINARY_DIR}")
1346 set(propertyName "${prefix}_populated")
1347 define_property(GLOBAL PROPERTY ${propertyName})
1348 set_property(GLOBAL PROPERTY ${propertyName} TRUE)
1353 # Set variables in the calling scope for any of the retrievable
1354 # properties. If no specific properties are requested, variables
1355 # will be set for all retrievable properties.
1357 # This function is intended to also be used by projects as the canonical
1358 # way to detect whether they should call FetchContent_Populate()
1359 # and pull the populated source into the build with add_subdirectory(),
1360 # if they are using the populated content in that way.
1361 function(FetchContent_GetProperties contentName)
1363 string(TOLOWER ${contentName} contentNameLower)
1366 set(oneValueArgs SOURCE_DIR BINARY_DIR POPULATED)
1367 set(multiValueArgs "")
1369 cmake_parse_arguments(ARG "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
1371 if(NOT ARG_SOURCE_DIR AND
1372 NOT ARG_BINARY_DIR AND
1374 # No specific properties requested, provide them all
1375 set(ARG_SOURCE_DIR ${contentNameLower}_SOURCE_DIR)
1376 set(ARG_BINARY_DIR ${contentNameLower}_BINARY_DIR)
1377 set(ARG_POPULATED ${contentNameLower}_POPULATED)
1380 set(prefix "_FetchContent_${contentNameLower}")
1383 set(propertyName "${prefix}_sourceDir")
1384 get_property(value GLOBAL PROPERTY ${propertyName})
1386 set(${ARG_SOURCE_DIR} ${value} PARENT_SCOPE)
1391 set(propertyName "${prefix}_binaryDir")
1392 get_property(value GLOBAL PROPERTY ${propertyName})
1394 set(${ARG_BINARY_DIR} ${value} PARENT_SCOPE)
1399 set(propertyName "${prefix}_populated")
1400 get_property(value GLOBAL PROPERTY ${propertyName} DEFINED)
1401 set(${ARG_POPULATED} ${value} PARENT_SCOPE)
1407 #=======================================================================
1408 # Performing the population
1409 #=======================================================================
1411 # The value of contentName will always have been lowercased by the caller.
1412 # All other arguments are assumed to be options that are understood by
1413 # ExternalProject_Add(), except for QUIET and SUBBUILD_DIR.
1414 function(__FetchContent_directPopulate contentName)
1423 # We need special processing if DOWNLOAD_NO_EXTRACT is true
1425 # Prevent the following from being passed through
1430 # We force these to be ON since we are always executing serially
1431 # and we want all steps to have access to the terminal in case they
1432 # need input from the command line (e.g. ask for a private key password)
1433 # or they want to provide timely progress. We silently absorb and
1434 # discard these if they are set by the caller.
1435 USES_TERMINAL_DOWNLOAD
1436 USES_TERMINAL_UPDATE
1439 set(multiValueArgs "")
1441 cmake_parse_arguments(PARSE_ARGV 1 ARG
1442 "${options}" "${oneValueArgs}" "${multiValueArgs}")
1444 if(NOT ARG_SUBBUILD_DIR)
1445 message(FATAL_ERROR "Internal error: SUBBUILD_DIR not set")
1446 elseif(NOT IS_ABSOLUTE "${ARG_SUBBUILD_DIR}")
1447 set(ARG_SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SUBBUILD_DIR}")
1450 if(NOT ARG_SOURCE_DIR)
1451 message(FATAL_ERROR "Internal error: SOURCE_DIR not set")
1452 elseif(NOT IS_ABSOLUTE "${ARG_SOURCE_DIR}")
1453 set(ARG_SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_SOURCE_DIR}")
1456 if(NOT ARG_BINARY_DIR)
1457 message(FATAL_ERROR "Internal error: BINARY_DIR not set")
1458 elseif(NOT IS_ABSOLUTE "${ARG_BINARY_DIR}")
1459 set(ARG_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${ARG_BINARY_DIR}")
1462 # Ensure the caller can know where to find the source and build directories
1463 # with some convenient variables. Doing this here ensures the caller sees
1464 # the correct result in the case where the default values are overridden by
1465 # the content details set by the project.
1466 set(${contentName}_SOURCE_DIR "${ARG_SOURCE_DIR}" PARENT_SCOPE)
1467 set(${contentName}_BINARY_DIR "${ARG_BINARY_DIR}" PARENT_SCOPE)
1469 # The unparsed arguments may contain spaces, so build up ARG_EXTRA
1470 # in such a way that it correctly substitutes into the generated
1471 # CMakeLists.txt file with each argument quoted.
1473 foreach(arg IN LISTS ARG_UNPARSED_ARGUMENTS)
1474 set(ARG_EXTRA "${ARG_EXTRA} \"${arg}\"")
1477 if(ARG_DOWNLOAD_NO_EXTRACT)
1478 set(ARG_EXTRA "${ARG_EXTRA} DOWNLOAD_NO_EXTRACT YES")
1479 set(__FETCHCONTENT_COPY_FILE
1481 ExternalProject_Get_Property(${contentName}-populate DOWNLOADED_FILE)
1482 get_filename_component(dlFileName \"\${DOWNLOADED_FILE}\" NAME)
1484 ExternalProject_Add_Step(${contentName}-populate copyfile
1485 COMMAND \"${CMAKE_COMMAND}\" -E copy_if_different
1486 \"<DOWNLOADED_FILE>\" \"${ARG_SOURCE_DIR}\"
1489 BYPRODUCTS \"${ARG_SOURCE_DIR}/\${dlFileName}\"
1490 COMMENT \"Copying file to SOURCE_DIR\"
1494 unset(__FETCHCONTENT_COPY_FILE)
1497 # Hide output if requested, but save it to a variable in case there's an
1498 # error so we can show the output upon failure. When not quiet, don't
1499 # capture the output to a variable because the user may want to see the
1500 # output as it happens (e.g. progress during long downloads). Combine both
1501 # stdout and stderr in the one capture variable so the output stays in order.
1504 OUTPUT_VARIABLE capturedOutput
1505 ERROR_VARIABLE capturedOutput
1510 message(STATUS "Populating ${contentName}")
1514 set(subCMakeOpts "-G${CMAKE_GENERATOR}")
1515 if(CMAKE_GENERATOR_PLATFORM)
1516 list(APPEND subCMakeOpts "-A${CMAKE_GENERATOR_PLATFORM}")
1518 if(CMAKE_GENERATOR_TOOLSET)
1519 list(APPEND subCMakeOpts "-T${CMAKE_GENERATOR_TOOLSET}")
1522 if(CMAKE_MAKE_PROGRAM)
1523 list(APPEND subCMakeOpts "-DCMAKE_MAKE_PROGRAM:FILEPATH=${CMAKE_MAKE_PROGRAM}")
1526 # Override the sub-build's configuration types for multi-config generators.
1527 # This ensures we are not affected by any custom setting from the project
1528 # and can always request a known configuration further below.
1529 get_property(is_multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
1531 list(APPEND subCMakeOpts "-DCMAKE_CONFIGURATION_TYPES:STRING=Debug")
1535 # Likely we've been invoked via CMake's script mode where no
1536 # generator is set (and hence CMAKE_MAKE_PROGRAM could not be
1537 # trusted even if provided). We will have to rely on being
1538 # able to find the default generator and build tool.
1542 set(__FETCHCONTENT_CACHED_INFO "")
1543 set(__passthrough_vars
1544 CMAKE_EP_GIT_REMOTE_UPDATE_STRATEGY
1550 foreach(var IN LISTS __passthrough_vars)
1552 # Embed directly in the generated CMakeLists.txt file to avoid making
1553 # the cmake command line excessively long. It also makes debugging and
1555 string(APPEND __FETCHCONTENT_CACHED_INFO "set(${var} [==[${${var}}]==])\n")
1559 # Avoid using if(... IN_LIST ...) so we don't have to alter policy settings
1560 list(FIND ARG_UNPARSED_ARGUMENTS GIT_REPOSITORY indexResult)
1561 if(indexResult GREATER_EQUAL 0)
1562 find_package(Git QUIET)
1563 string(APPEND __FETCHCONTENT_CACHED_INFO "
1564 # Pass through things we've already detected in the main project to avoid
1565 # paying the cost of redetecting them again in ExternalProject_Add()
1566 set(GIT_EXECUTABLE [==[${GIT_EXECUTABLE}]==])
1567 set(GIT_VERSION_STRING [==[${GIT_VERSION_STRING}]==])
1568 set_property(GLOBAL PROPERTY _CMAKE_FindGit_GIT_EXECUTABLE_VERSION
1569 [==[${GIT_EXECUTABLE};${GIT_VERSION_STRING}]==]
1574 # Create and build a separate CMake project to carry out the population.
1575 # If we've already previously done these steps, they will not cause
1576 # anything to be updated, so extra rebuilds of the project won't occur.
1577 # Make sure to pass through CMAKE_MAKE_PROGRAM in case the main project
1578 # has this set to something not findable on the PATH. We also ensured above
1579 # that the Debug config will be defined for multi-config generators.
1580 configure_file("${CMAKE_CURRENT_FUNCTION_LIST_DIR}/FetchContent/CMakeLists.cmake.in"
1581 "${ARG_SUBBUILD_DIR}/CMakeLists.txt")
1583 COMMAND ${CMAKE_COMMAND} ${subCMakeOpts} .
1584 RESULT_VARIABLE result
1586 WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
1590 message("${capturedOutput}")
1592 message(FATAL_ERROR "CMake step for ${contentName} failed: ${result}")
1595 COMMAND ${CMAKE_COMMAND} --build . --config Debug
1596 RESULT_VARIABLE result
1598 WORKING_DIRECTORY "${ARG_SUBBUILD_DIR}"
1602 message("${capturedOutput}")
1604 message(FATAL_ERROR "Build step for ${contentName} failed: ${result}")
1610 option(FETCHCONTENT_FULLY_DISCONNECTED "Disables all attempts to download or update content and assumes source dirs already exist")
1611 option(FETCHCONTENT_UPDATES_DISCONNECTED "Enables UPDATE_DISCONNECTED behavior for all content population")
1612 option(FETCHCONTENT_QUIET "Enables QUIET option for all content population" ON)
1613 set(FETCHCONTENT_BASE_DIR "${CMAKE_BINARY_DIR}/_deps" CACHE PATH "Directory under which to collect all populated content")
1615 # Populate the specified content using details stored from
1616 # an earlier call to FetchContent_Declare().
1617 function(FetchContent_Populate contentName)
1620 message(FATAL_ERROR "Empty contentName not allowed for FetchContent_Populate()")
1623 string(TOLOWER ${contentName} contentNameLower)
1626 # This is the direct population form with details fully specified
1627 # as part of the call, so we already have everything we need
1628 __FetchContent_directPopulate(
1630 SUBBUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-subbuild"
1631 SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-src"
1632 BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/${contentNameLower}-build"
1633 ${ARGN} # Could override any of the above ..._DIR variables
1636 # Pass source and binary dir variables back to the caller
1637 set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
1638 set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
1640 # Don't set global properties, or record that we did this population, since
1641 # this was a direct call outside of the normal declared details form.
1642 # We only want to save values in the global properties for content that
1643 # honors the hierarchical details mechanism so that projects are not
1644 # robbed of the ability to override details set in nested projects.
1648 # No details provided, so assume they were saved from an earlier call
1649 # to FetchContent_Declare(). Do a check that we haven't already
1650 # populated this content before in case the caller forgot to check.
1651 FetchContent_GetProperties(${contentName})
1652 if(${contentNameLower}_POPULATED)
1653 if("${${contentNameLower}_SOURCE_DIR}" STREQUAL "")
1655 "Content ${contentName} already populated by find_package() or a "
1656 "dependency provider"
1660 "Content ${contentName} already populated in ${${contentNameLower}_SOURCE_DIR}"
1665 __FetchContent_getSavedDetails(${contentName} contentDetails)
1666 if("${contentDetails}" STREQUAL "")
1667 message(FATAL_ERROR "No details have been set for content: ${contentName}")
1670 string(TOUPPER ${contentName} contentNameUpper)
1671 set(FETCHCONTENT_SOURCE_DIR_${contentNameUpper}
1672 "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}"
1673 CACHE PATH "When not empty, overrides where to find pre-populated content for ${contentName}")
1675 if(FETCHCONTENT_SOURCE_DIR_${contentNameUpper})
1676 # The source directory has been explicitly provided in the cache,
1677 # so no population is required. The build directory may still be specified
1678 # by the declared details though.
1680 if(NOT IS_ABSOLUTE "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
1681 # Don't check this directory because we don't know what location it is
1682 # expected to be relative to. We can't make this a hard error for backward
1683 # compatibility reasons.
1684 message(WARNING "Relative source directory specified. This is not safe, "
1685 "as it depends on the calling directory scope.\n"
1686 " FETCHCONTENT_SOURCE_DIR_${contentNameUpper} --> ${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
1687 elseif(NOT EXISTS "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
1688 message(FATAL_ERROR "Manually specified source directory is missing:\n"
1689 " FETCHCONTENT_SOURCE_DIR_${contentNameUpper} --> ${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
1692 set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_SOURCE_DIR_${contentNameUpper}}")
1694 cmake_parse_arguments(savedDetails "" "BINARY_DIR" "" ${contentDetails})
1696 if(savedDetails_BINARY_DIR)
1697 set(${contentNameLower}_BINARY_DIR ${savedDetails_BINARY_DIR})
1699 set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
1702 elseif(FETCHCONTENT_FULLY_DISCONNECTED)
1703 # Bypass population and assume source is already there from a previous run.
1704 # Declared details may override the default source or build directories.
1706 cmake_parse_arguments(savedDetails "" "SOURCE_DIR;BINARY_DIR" "" ${contentDetails})
1708 if(savedDetails_SOURCE_DIR)
1709 set(${contentNameLower}_SOURCE_DIR ${savedDetails_SOURCE_DIR})
1711 set(${contentNameLower}_SOURCE_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src")
1714 if(savedDetails_BINARY_DIR)
1715 set(${contentNameLower}_BINARY_DIR ${savedDetails_BINARY_DIR})
1717 set(${contentNameLower}_BINARY_DIR "${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build")
1721 # Support both a global "disconnect all updates" and a per-content
1722 # update test (either one being set disables updates for this content).
1723 option(FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper}
1724 "Enables UPDATE_DISCONNECTED behavior just for population of ${contentName}")
1725 if(FETCHCONTENT_UPDATES_DISCONNECTED OR
1726 FETCHCONTENT_UPDATES_DISCONNECTED_${contentNameUpper})
1727 set(disconnectUpdates True)
1729 set(disconnectUpdates False)
1732 if(FETCHCONTENT_QUIET)
1733 set(quietFlag QUIET)
1738 set(__detailsQuoted)
1739 foreach(__item IN LISTS contentDetails)
1740 if(NOT __item STREQUAL "OVERRIDE_FIND_PACKAGE")
1741 string(APPEND __detailsQuoted " [==[${__item}]==]")
1744 cmake_language(EVAL CODE "
1745 __FetchContent_directPopulate(
1748 UPDATE_DISCONNECTED ${disconnectUpdates}
1749 SUBBUILD_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-subbuild\"
1750 SOURCE_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-src\"
1751 BINARY_DIR \"${FETCHCONTENT_BASE_DIR}/${contentNameLower}-build\"
1752 # Put the saved details last so they can override any of the
1753 # the options we set above (this can include SOURCE_DIR or
1760 FetchContent_SetPopulated(
1762 SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}"
1763 BINARY_DIR "${${contentNameLower}_BINARY_DIR}"
1766 # Pass variables back to the caller. The variables passed back here
1767 # must match what FetchContent_GetProperties() sets when it is called
1768 # with just the content name.
1769 set(${contentNameLower}_SOURCE_DIR "${${contentNameLower}_SOURCE_DIR}" PARENT_SCOPE)
1770 set(${contentNameLower}_BINARY_DIR "${${contentNameLower}_BINARY_DIR}" PARENT_SCOPE)
1771 set(${contentNameLower}_POPULATED True PARENT_SCOPE)
1775 function(__FetchContent_setupFindPackageRedirection contentName)
1777 __FetchContent_getSavedDetails(${contentName} contentDetails)
1779 string(TOLOWER ${contentName} contentNameLower)
1780 get_property(wantFindPackage GLOBAL PROPERTY
1781 _FetchContent_${contentNameLower}_find_package_args
1785 # Avoid using if(... IN_LIST ...) so we don't have to alter policy settings
1786 list(FIND contentDetails OVERRIDE_FIND_PACKAGE indexResult)
1787 if(NOT wantFindPackage AND indexResult EQUAL -1)
1788 # No find_package() redirection allowed
1792 # We write out dep-config.cmake and dep-config-version.cmake file name
1793 # forms here because they are forced to lowercase. FetchContent
1794 # dependency names are case-insensitive, but find_package() config files
1795 # are only case-insensitive for the -config and -config-version forms,
1796 # not the Config and ConfigVersion forms.
1797 set(inFileDir ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/FetchContent)
1798 set(configFilePrefix1 "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/${contentName}Config")
1799 set(configFilePrefix2 "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/${contentNameLower}-config")
1800 if(NOT EXISTS "${configFilePrefix1}.cmake" AND
1801 NOT EXISTS "${configFilePrefix2}.cmake")
1802 configure_file(${inFileDir}/package-config.cmake.in
1803 "${configFilePrefix2}.cmake" @ONLY
1806 if(NOT EXISTS "${configFilePrefix1}Version.cmake" AND
1807 NOT EXISTS "${configFilePrefix2}-version.cmake")
1808 configure_file(${inFileDir}/package-config-version.cmake.in
1809 "${configFilePrefix2}-version.cmake" @ONLY
1813 # Now that we've created the redirected package config files, prevent
1814 # find_package() from delegating to FetchContent and let it find these
1815 # config files through its normal processing.
1816 set(propertyName "${prefix}_override_find_package")
1817 set(GLOBAL PROPERTY ${propertyName} FALSE)
1818 set(${contentName}_DIR "${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}"
1819 CACHE INTERNAL "Redirected by FetchContent"
1824 # Arguments are assumed to be the names of dependencies that have been
1825 # declared previously and should be populated. It is not an error if
1826 # any of them have already been populated (they will just be skipped in
1827 # that case). The command is implemented as a macro so that the variables
1828 # defined by the FetchContent_GetProperties() and FetchContent_Populate()
1829 # calls will be available to the caller.
1830 macro(FetchContent_MakeAvailable)
1832 # We must append an item, even if the variable is unset, so prefix its value.
1833 # We will strip that prefix when we pop the value at the end of the macro.
1834 list(APPEND __cmake_fcCurrentVarsStack
1835 "__fcprefix__${CMAKE_VERIFY_INTERFACE_HEADER_SETS}"
1837 set(CMAKE_VERIFY_INTERFACE_HEADER_SETS FALSE)
1839 get_property(__cmake_providerCommand GLOBAL PROPERTY
1840 __FETCHCONTENT_MAKEAVAILABLE_SERIAL_PROVIDER
1842 foreach(__cmake_contentName IN ITEMS ${ARGV})
1843 string(TOLOWER ${__cmake_contentName} __cmake_contentNameLower)
1845 # If user specified FETCHCONTENT_SOURCE_DIR_... for this dependency, that
1846 # overrides everything else and we shouldn't try to use find_package() or
1847 # a dependency provider.
1848 string(TOUPPER ${__cmake_contentName} __cmake_contentNameUpper)
1849 if("${FETCHCONTENT_SOURCE_DIR_${__cmake_contentNameUpper}}" STREQUAL "")
1850 # Dependency provider gets first opportunity, but prevent infinite
1851 # recursion if we are called again for the same thing
1852 if(NOT "${__cmake_providerCommand}" STREQUAL "" AND
1853 NOT DEFINED __cmake_fcProvider_${__cmake_contentNameLower})
1855 "Trying FETCHCONTENT_MAKEAVAILABLE_SERIAL dependency provider for "
1856 "${__cmake_contentName}"
1858 # It's still valid if there are no saved details. The project may have
1859 # been written to assume a dependency provider is always set and will
1860 # provide dependencies without having any declared details for them.
1861 __FetchContent_getSavedDetails(${__cmake_contentName} __cmake_contentDetails)
1862 set(__cmake_providerArgs
1863 "FETCHCONTENT_MAKEAVAILABLE_SERIAL"
1864 "${__cmake_contentName}"
1866 # Empty arguments must be preserved because of things like
1867 # GIT_SUBMODULES (see CMP0097)
1868 foreach(__cmake_item IN LISTS __cmake_contentDetails)
1869 string(APPEND __cmake_providerArgs " [==[${__cmake_item}]==]")
1872 # This property might be defined but empty. As long as it is defined,
1873 # find_package() can be called.
1874 get_property(__cmake_addfpargs GLOBAL PROPERTY
1875 _FetchContent_${contentNameLower}_find_package_args
1878 if(__cmake_addfpargs)
1879 get_property(__cmake_fpargs GLOBAL PROPERTY
1880 _FetchContent_${contentNameLower}_find_package_args
1882 string(APPEND __cmake_providerArgs " FIND_PACKAGE_ARGS")
1883 foreach(__cmake_item IN LISTS __cmake_fpargs)
1884 string(APPEND __cmake_providerArgs " [==[${__cmake_item}]==]")
1888 # Calling the provider could lead to FetchContent_MakeAvailable() being
1889 # called for a nested dependency. That nested call may occur in the
1890 # current variable scope. We have to save and restore the variables we
1892 list(APPEND __cmake_fcCurrentVarsStack
1893 ${__cmake_contentName}
1894 ${__cmake_contentNameLower}
1897 set(__cmake_fcProvider_${__cmake_contentNameLower} YES)
1898 cmake_language(EVAL CODE "${__cmake_providerCommand}(${__cmake_providerArgs})")
1900 list(POP_BACK __cmake_fcCurrentVarsStack
1901 __cmake_contentNameLower
1905 unset(__cmake_fcProvider_${__cmake_contentNameLower})
1906 unset(__cmake_providerArgs)
1907 unset(__cmake_addfpargs)
1908 unset(__cmake_fpargs)
1910 unset(__cmake_contentDetails)
1912 FetchContent_GetProperties(${__cmake_contentName})
1913 if(${__cmake_contentNameLower}_POPULATED)
1918 # Check if we've been asked to try find_package() first, even if we
1919 # have already populated this dependency. If we previously tried to
1920 # use find_package() for this and it succeeded, those things might
1921 # no longer be in scope, so we have to do it again.
1922 get_property(__cmake_haveFpArgs GLOBAL PROPERTY
1923 _FetchContent_${__cmake_contentNameLower}_find_package_args DEFINED
1925 if(__cmake_haveFpArgs)
1926 unset(__cmake_haveFpArgs)
1927 message(VERBOSE "Trying find_package(${__cmake_contentName} ...) before FetchContent")
1928 get_property(__cmake_fpArgs GLOBAL PROPERTY
1929 _FetchContent_${__cmake_contentNameLower}_find_package_args
1932 # This call could lead to FetchContent_MakeAvailable() being called for
1933 # a nested dependency and it may occur in the current variable scope.
1934 # We have to save/restore the variables we need to preserve.
1935 list(APPEND __cmake_fcCurrentNameStack
1936 ${__cmake_contentName}
1937 ${__cmake_contentNameLower}
1939 find_package(${__cmake_contentName} ${__cmake_fpArgs})
1940 list(POP_BACK __cmake_fcCurrentNameStack
1941 __cmake_contentNameLower
1944 unset(__cmake_fpArgs)
1946 if(${__cmake_contentName}_FOUND)
1947 FetchContent_SetPopulated(${__cmake_contentName})
1948 FetchContent_GetProperties(${__cmake_contentName})
1953 unset(__cmake_haveFpArgs)
1956 FetchContent_GetProperties(${__cmake_contentName})
1957 if(NOT ${__cmake_contentNameLower}_POPULATED)
1958 FetchContent_Populate(${__cmake_contentName})
1959 __FetchContent_setupFindPackageRedirection(${__cmake_contentName})
1961 # Only try to call add_subdirectory() if the populated content
1962 # can be treated that way. Protecting the call with the check
1963 # allows this function to be used for projects that just want
1964 # to ensure the content exists, such as to provide content at
1965 # a known location. We check the saved details for an optional
1966 # SOURCE_SUBDIR which can be used in the same way as its meaning
1967 # for ExternalProject. It won't matter if it was passed through
1968 # to the ExternalProject sub-build, since it would have been
1970 set(__cmake_srcdir "${${__cmake_contentNameLower}_SOURCE_DIR}")
1971 __FetchContent_getSavedDetails(${__cmake_contentName} __cmake_contentDetails)
1972 if("${__cmake_contentDetails}" STREQUAL "")
1973 message(FATAL_ERROR "No details have been set for content: ${__cmake_contentName}")
1975 cmake_parse_arguments(__cmake_arg "" "SOURCE_SUBDIR" "" ${__cmake_contentDetails})
1976 if(NOT "${__cmake_arg_SOURCE_SUBDIR}" STREQUAL "")
1977 string(APPEND __cmake_srcdir "/${__cmake_arg_SOURCE_SUBDIR}")
1980 if(EXISTS ${__cmake_srcdir}/CMakeLists.txt)
1981 add_subdirectory(${__cmake_srcdir} ${${__cmake_contentNameLower}_BINARY_DIR})
1984 unset(__cmake_srcdir)
1985 unset(__cmake_contentDetails)
1986 unset(__cmake_arg_SOURCE_SUBDIR)
1990 # Prefix will be "__fcprefix__"
1991 list(POP_BACK __cmake_fcCurrentVarsStack __cmake_original_verify_setting)
1992 string(SUBSTRING "${__cmake_original_verify_setting}"
1993 12 -1 __cmake_original_verify_setting
1995 set(CMAKE_VERIFY_INTERFACE_HEADER_SETS ${__cmake_original_verify_setting})
1997 # clear local variables to prevent leaking into the caller's scope
1998 unset(__cmake_contentName)
1999 unset(__cmake_contentNameLower)
2000 unset(__cmake_contentNameUpper)
2001 unset(__cmake_providerCommand)
2002 unset(__cmake_original_verify_setting)