FetchContent¶
在 3.11 版被加入.
This module provides commands to populate content at configure time or as part of the calling script.
在 CMake 中使用以下命令載入該模組:
include(FetchContent)
備註
The Using Dependencies Guide provides a high-level
introduction to this general topic. It provides a broader overview of
where the FetchContent module fits into the bigger picture,
including its relationship to the find_package() command.
The guide is recommended pre-reading before moving on to the details below.
概覽¶
This module enables populating content at configure time via any method
supported by the ExternalProject module. Whereas
ExternalProject_Add() downloads at build time, the
FetchContent module makes content available immediately, allowing the
configure step to use the content in commands like add_subdirectory(),
include() or file() operations.
Content population details should be defined separately from the command that performs the actual population. This separation ensures that all the dependency details are defined before anything might try to use them to populate content. This is particularly important in more complex project hierarchies where dependencies may be shared between multiple projects.
The following shows a typical example of declaring content details for some dependencies and then ensuring they are populated with a separate call:
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
)
FetchContent_Declare(
myCompanyIcons
URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz
URL_HASH MD5=5588a7b18261c20068beabfb4f530b87
)
FetchContent_MakeAvailable(googletest myCompanyIcons)
The FetchContent_MakeAvailable() command ensures the named
dependencies have been populated, either by an earlier call, or by populating
them itself. When performing the population, it will also add them to the
main build, if possible, so that the main build can use the populated
projects' targets, etc. See the command's documentation for how these steps
are performed.
When using a hierarchical project arrangement, projects at higher levels in the hierarchy are able to override the declared details of content specified anywhere lower in the project hierarchy. The first details to be declared for a given dependency take precedence, regardless of where in the project hierarchy that occurs. Similarly, the first call that tries to populate a dependency "wins", with subsequent populations reusing the result of the first instead of repeating the population again. See the Examples which demonstrate this scenario.
The FetchContent module also supports defining and populating
content in a single call, with no check for whether the content has been
populated elsewhere already. This should not be done in projects, but may
be appropriate for populating content in
CMake script mode.
See FetchContent_Populate() for details.
命令¶
- FetchContent_Declare¶
FetchContent_Declare( <name> <contentOptions>... [EXCLUDE_FROM_ALL] [SYSTEM] [OVERRIDE_FIND_PACKAGE | FIND_PACKAGE_ARGS args...] )
The
FetchContent_Declare()function records the options that describe how to populate the specified content. If such details have already been recorded earlier in this project (regardless of where in the project hierarchy), this and all later calls for the same content<name>are ignored. This "first to record, wins" approach is what allows hierarchical projects to have parent projects override content details of child projects.The content
<name>can be any string without spaces, but good practice would be to use only letters, numbers, and underscores. The name will be treated case-insensitively, and it should be obvious for the content it represents. It is often the name of the child project, or the value given to its top levelproject()command (if it is a CMake project). For well-known public projects, the name should generally be the official name of the project. Choosing an unusual name makes it unlikely that other projects needing that same content will use the same name, leading to the content being populated multiple times.The
<contentOptions>can be any of the download, update, or patch options that theExternalProject_Add()command understands. The configure, build, install, and test steps are explicitly disabled, so options related to those steps are prohibited and will be discarded if given. TheSOURCE_SUBDIRoption is an exception, seeFetchContent_MakeAvailable()for details on how that affects behavior.在 3.30 版的變更: When policy
CMP0168is set toNEW, some output-related and directory-related options are ignored. See the policy documentation for details.In most cases,
<contentOptions>will just be a couple of options defining the download method and method-specific details like a commit tag or archive hash. For example:FetchContent_Declare( googletest GIT_REPOSITORY https://github.com/google/googletest.git GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0 ) FetchContent_Declare( myCompanyIcons URL https://intranet.mycompany.com/assets/iconset_1.12.tar.gz URL_HASH MD5=5588a7b18261c20068beabfb4f530b87 ) FetchContent_Declare( myCompanyCertificates SVN_REPOSITORY svn+ssh://svn.mycompany.com/srv/svn/trunk/certs SVN_REVISION -r12345 )
Where contents are being fetched from a remote location and you do not control that server, it is advisable to use a hash for
GIT_TAGrather than a branch or tag name. A commit hash is more secure and helps to confirm that the downloaded contents are what you expected.在 3.14 版的變更: Commands for the download, update, or patch steps can access the terminal. This may be needed for things like password prompts or real-time display of command progress.
在 3.22 版被加入: The
CMAKE_TLS_VERIFY,CMAKE_TLS_CAINFO,CMAKE_NETRC, andCMAKE_NETRC_FILEvariables now provide the defaults for their corresponding content options, just like they do forExternalProject_Add(). Previously, these variables were ignored by theFetchContentmodule.在 3.24 版被加入:
FIND_PACKAGE_ARGSThis option is for scenarios where the
FetchContent_MakeAvailable()command may first try a call tofind_package()to satisfy the dependency for<name>. By default, such a call would be simplyfind_package(<name>), butFIND_PACKAGE_ARGScan be used to provide additional arguments to be appended after the<name>.FIND_PACKAGE_ARGScan also be given with nothing after it, which indicates thatfind_package()can still be called ifFETCHCONTENT_TRY_FIND_PACKAGE_MODEis set toOPT_IN, or is not set.It would not normally be appropriate to specify
REQUIREDas one of the additional arguments afterFIND_PACKAGE_ARGS. Doing so would mean thefind_package()call must succeed, so none of the other details specified in theFetchContent_Declare()call would get a chance to be used as a fall-back.Everything after the
FIND_PACKAGE_ARGSkeyword is appended to thefind_package()call, so all other<contentOptions>must come before theFIND_PACKAGE_ARGSkeyword. If theCMAKE_FIND_PACKAGE_TARGETS_GLOBALvariable is set to true at the timeFetchContent_Declare()is called, aGLOBALkeyword will be appended to thefind_package()arguments if it was not already specified. It will also be appended ifFIND_PACKAGE_ARGSwas not given, butFETCHCONTENT_TRY_FIND_PACKAGE_MODEwas set toALWAYS.OVERRIDE_FIND_PACKAGEcannot be used whenFIND_PACKAGE_ARGSis given.Dependency Providers discusses another way that
FetchContent_MakeAvailable()calls can be redirected.FIND_PACKAGE_ARGSis intended for project control, whereas dependency providers allow users to override project behavior.OVERRIDE_FIND_PACKAGEWhen a
FetchContent_Declare(<name> ...)call includes this option, subsequent calls tofind_package(<name> ...)will ensure thatFetchContent_MakeAvailable(<name>)has been called, then use the config package files in theCMAKE_FIND_PACKAGE_REDIRECTS_DIRdirectory (which are usually created byFetchContent_MakeAvailable()). This effectively makesFetchContent_MakeAvailable()overridefind_package()for the named dependency, allowing the former to satisfy the package requirements of the latter.FIND_PACKAGE_ARGScannot be used whenOVERRIDE_FIND_PACKAGEis given.If a dependency provider has been set and the project calls
find_package()for the<name>dependency,OVERRIDE_FIND_PACKAGEwill not prevent the provider from seeing that call. Dependency providers always have the opportunity to intercept any direct call tofind_package(), except if that call contains theBYPASS_PROVIDERoption.
在 3.25 版被加入:
SYSTEMIf the
SYSTEMargument is provided, theSYSTEMdirectory property of a subdirectory added byFetchContent_MakeAvailable()will be set to true. This will affect non-imported targets created as part of that command. See theSYSTEMtarget property documentation for a more detailed discussion of the effects.
在 3.28 版被加入:
EXCLUDE_FROM_ALLIf the
EXCLUDE_FROM_ALLargument is provided, then targets in the subdirectory added byFetchContent_MakeAvailable()will not be included in theALLtarget by default, and may be excluded from IDE project files. See the documentation for the directory propertyEXCLUDE_FROM_ALLfor a detailed discussion of the effects.
- FetchContent_MakeAvailable¶
在 3.14 版被加入.
FetchContent_MakeAvailable(<name1> [<name2>...])
This command ensures that each of the named dependencies are made available to the project by the time it returns. There must have been a call to
FetchContent_Declare()for each dependency, and the first such call will control how that dependency will be made available, as described below.If
<lowercaseName>_SOURCE_DIRis not set:在 3.24 版被加入: If a dependency provider is set, call the provider's command with
FETCHCONTENT_MAKEAVAILABLE_SERIALas the first argument, followed by the arguments of the first call toFetchContent_Declare()for<name>. IfSOURCE_DIRorBINARY_DIRwere not part of the original declared arguments, they will be added with their default values. IfFETCHCONTENT_TRY_FIND_PACKAGE_MODEwas set toNEVERwhen the details were declared, anyFIND_PACKAGE_ARGSwill be omitted. TheOVERRIDE_FIND_PACKAGEkeyword is also always omitted. If the provider fulfilled the request,FetchContent_MakeAvailable()will consider that dependency handled, skip the remaining steps below, and move on to the next dependency in the list.在 3.24 版被加入: If permitted,
find_package(<name> [<args>...])will be called, where<args>...may be provided by theFIND_PACKAGE_ARGSoption inFetchContent_Declare(). The value of theFETCHCONTENT_TRY_FIND_PACKAGE_MODEvariable at the timeFetchContent_Declare()was called determines whetherFetchContent_MakeAvailable()can callfind_package(). If theCMAKE_FIND_PACKAGE_TARGETS_GLOBALvariable is set to true whenFetchContent_MakeAvailable()is called, it still affects any imported targets created when that in turn callsfind_package(), even if that variable was false when the corresponding details were declared.
If the dependency was not satisfied by a provider or a
find_package()call,FetchContent_MakeAvailable()then uses the following logic to make the dependency available:If the dependency has already been populated earlier in this run, set the
<lowercaseName>_POPULATED,<lowercaseName>_SOURCE_DIR, and<lowercaseName>_BINARY_DIRvariables in the same way as a call toFetchContent_GetProperties(), then skip the remaining steps below and move on to the next dependency in the list.Populate the dependency using the details recorded by an earlier call to
FetchContent_Declare(). Halt with a fatal error if no such details have been recorded.FETCHCONTENT_SOURCE_DIR_<uppercaseName>can be used to override the declared details and use content provided at the specified location instead.在 3.24 版被加入: Ensure the
CMAKE_FIND_PACKAGE_REDIRECTS_DIRdirectory contains a<lowercaseName>-config.cmakeand a<lowercaseName>-config-version.cmakefile (or equivalently,<name>Config.cmakeand<name>ConfigVersion.cmake). The directory that theCMAKE_FIND_PACKAGE_REDIRECTS_DIRvariable points to is cleared at the start of every CMake run. If no config file exists after populating the dependency in the previous step, a minimal one will be written whichincludesany<lowercaseName>-extra.cmakeor<name>Extra.cmakefile with theOPTIONALflag (so the files can be missing and won't generate a warning). Similarly, if no config version file exists, a very simple one will be written which setsPACKAGE_VERSION_COMPATIBLEandPACKAGE_VERSION_EXACTto true. This ensures all future calls tofind_package()for the dependency will use the redirected config file, regardless of any version requirements. CMake cannot automatically determine an arbitrary dependency's version, so it cannot setPACKAGE_VERSION. When a dependency is pulled in viaadd_subdirectory()in the next step, it may choose to overwrite the generated config version file inCMAKE_FIND_PACKAGE_REDIRECTS_DIRwith one that also setsPACKAGE_VERSION. The dependency may also write a<lowercaseName>-extra.cmakeor<name>Extra.cmakefile to perform custom processing, or define any variables that their normal (installed) package config file would otherwise usually define (many projects don't do any custom processing or set any variables and therefore have no need to do this). If required, the main project can write these files instead if the dependency project doesn't do so. This allows the main project to add missing details from older dependencies that haven't or can't be updated to support this functionality. See Integrating With find_package() for examples.If the top directory of the populated content contains a
CMakeLists.txtfile, calladd_subdirectory()to add it to the main build. It is not an error for there to be noCMakeLists.txtfile, which allows the command to be used for dependencies that make downloaded content available at a known location, but which do not need or support being added directly to the build.在 3.18 版被加入: The
SOURCE_SUBDIRoption can be given in the declared details to look somewhere below the top directory instead (i.e. the same way thatSOURCE_SUBDIRis used by theExternalProject_Add()command). The path provided withSOURCE_SUBDIRmust be relative, and it will be treated as relative to the top directory. It can also point to a directory that does not contain aCMakeLists.txtfile, or even to a directory that doesn't exist. This can be used to avoid adding a project that contains aCMakeLists.txtfile in its top directory.在 3.25 版被加入: If the
SYSTEMkeyword was included in the call toFetchContent_Declare(), theSYSTEMkeyword will be added to theadd_subdirectory()command.在 3.28 版被加入: If the
EXCLUDE_FROM_ALLkeyword was included in the call toFetchContent_Declare(), theEXCLUDE_FROM_ALLkeyword will be added to theadd_subdirectory()command.在 3.29 版被加入:
CMAKE_EXPORT_FIND_PACKAGE_NAMEis set to the dependency name before callingadd_subdirectory().
Projects should aim to declare the details of all dependencies they might use before they call
FetchContent_MakeAvailable()for any of them. This ensures that if any of the dependencies are also sub-dependencies of one or more of the others, the main project still controls the details that will be used (because it will declare them first before the dependencies get a chance to). In the following code samples, assume that theuses_otherdependency also usesFetchContentto add theotherdependency internally:# WRONG: Should declare all details first FetchContent_Declare(uses_other ...) FetchContent_MakeAvailable(uses_other) FetchContent_Declare(other ...) # Will be ignored, uses_other beat us to it FetchContent_MakeAvailable(other) # Would use details declared by uses_other
# CORRECT: All details declared first, so they will take priority FetchContent_Declare(uses_other ...) FetchContent_Declare(other ...) FetchContent_MakeAvailable(uses_other other)
Note that
CMAKE_VERIFY_INTERFACE_HEADER_SETSis explicitly set to false upon entry toFetchContent_MakeAvailable(), and is restored to its original value before the command returns. Developers typically only want to verify header sets from the main project, not those from any dependencies. This local manipulation of theCMAKE_VERIFY_INTERFACE_HEADER_SETSvariable provides that intuitive behavior. You can use variables likeCMAKE_PROJECT_INCLUDEorCMAKE_PROJECT_<PROJECT-NAME>_INCLUDEto turn verification back on for all or some dependencies. You can also set theVERIFY_INTERFACE_HEADER_SETSproperty of individual targets.
- FetchContent_Populate¶
The
FetchContent_Populate()command is a self-contained call which can be used to perform content population as an isolated operation. It is rarely the right command to use, projects should almost always useFetchContent_Declare()andFetchContent_MakeAvailable()instead. The main use case forFetchContent_Populate()is in CMake script mode as part of implementing some other higher level custom feature.FetchContent_Populate( <name> [QUIET] [SUBBUILD_DIR <subBuildDir>] [SOURCE_DIR <srcDir>] [BINARY_DIR <binDir>] ... )
At least one option must be specified after <name>, otherwise the call is interpreted differently (see below). The supported options for
FetchContent_Populate()are the same as those forFetchContent_Declare(), with a few exceptions. The following do not relate to populating content withFetchContent_Populate()and therefore are not supported:EXCLUDE_FROM_ALLSYSTEMOVERRIDE_FIND_PACKAGEFIND_PACKAGE_ARGS
The few options shown in the signature above are either specific to
FetchContent_Populate(), or their behavior is slightly modified from howExternalProject_Add()treats them:QUIETThe
QUIEToption can be given to hide the output associated with populating the specified content. If the population fails, the output will be shown regardless of whether this option was given or not so that the cause of the failure can be diagnosed. TheFETCHCONTENT_QUIETvariable has no effect onFetchContent_Populate()calls of this form where the content details are provided directly.在 3.30 版的變更: The
QUIEToption andFETCHCONTENT_QUIETvariable have no effect when policyCMP0168is set toNEW. The output is still quiet by default in that case, but verbosity is controlled by the message logging level (seeCMAKE_MESSAGE_LOG_LEVELand--log-level).SUBBUILD_DIRThe
SUBBUILD_DIRargument can be provided to change the location of the sub-build created to perform the population. The default value is${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-subbuild, and it would be unusual to need to override this default. If a relative path is specified, it will be interpreted as relative toCMAKE_CURRENT_BINARY_DIR. This option should not be confused with theSOURCE_SUBDIRoption, which only affects theFetchContent_MakeAvailable()command.在 3.30 版的變更:
SUBBUILD_DIRis ignored when policyCMP0168is set toNEW, since there is no sub-build in that case.SOURCE_DIR,BINARY_DIRThe
SOURCE_DIRandBINARY_DIRarguments are supported byExternalProject_Add(), but different default values are used byFetchContent_Populate().SOURCE_DIRdefaults to${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-src, andBINARY_DIRdefaults to${CMAKE_CURRENT_BINARY_DIR}/<lowercaseName>-build. If a relative path is specified, it will be interpreted as relative toCMAKE_CURRENT_BINARY_DIR.
In addition to the above explicit options, any other unrecognized options are passed through unmodified to
ExternalProject_Add()to set up the download, patch, and update steps. The following options are explicitly prohibited (they are disabled by theFetchContent_Populate()command):CONFIGURE_COMMANDBUILD_COMMANDINSTALL_COMMANDTEST_COMMAND
With this form, the
FETCHCONTENT_FULLY_DISCONNECTEDandFETCHCONTENT_UPDATES_DISCONNECTEDvariables and policyCMP0170are ignored.When this form of
FetchContent_Populate()returns, the following variables will be set in the scope of the caller:<lowercaseName>_SOURCE_DIRThe location where the populated content can be found upon return.
<lowercaseName>_BINARY_DIRA directory originally intended for use as a corresponding build directory, but is unlikely to be relevant when using this form of the command.
If using
FetchContent_Populate()within CMake script mode, be aware that the implementation sets up a sub-build which therefore requires a CMake generator and build tool to be available. If these cannot be found by default, then theCMAKE_GENERATORand potentially theCMAKE_MAKE_PROGRAMvariables will need to be set appropriately on the command line invoking the script.在 3.30 版的變更: If policy
CMP0168is set toNEW, no sub-build is used. Within CMake script mode, that allowsFetchContent_Populate()to be called without any build tool or CMake generator.在 3.18 版被加入: Added support for the
DOWNLOAD_NO_EXTRACToption.
The command supports another form, although it should no longer be used:
FetchContent_Populate(<name>)在 3.30 版的變更: This form is deprecated. Policy
CMP0169provides backward compatibility for projects that still need to use this form, but projects should be updated to useFetchContent_MakeAvailable()instead.In this form, the only argument given to
FetchContent_Populate()is the<name>. When used this way, the command assumes the content details have been recorded by an earlier call toFetchContent_Declare(). The details are stored in a global property, so they are unaffected by things like variable or directory scope. Therefore, it doesn't matter where in the project the details were previously declared, as long as they have been declared before the call toFetchContent_Populate(). Those saved details are then used to populate the content using a method based onExternalProject_Add()(see policyCMP0168for important behavioral aspects of how that is done).When this form of
FetchContent_Populate()returns, the following variables will be set in the scope of the caller:
<lowercaseName>_POPULATEDThis will always be set to
TRUEby the call.<lowercaseName>_SOURCE_DIRThe location where the populated content can be found upon return.
<lowercaseName>_BINARY_DIRA directory intended for use as a corresponding build directory.
The values of the three variables can also be retrieved from anywhere in the project hierarchy using the
FetchContent_GetProperties()command.The implementation ensures that if the content has already been populated in a previous CMake run, that content will be reused rather than repopulating again. For the common case where population involves downloading content, the cost of the download is only paid once. But note that it is an error to call
FetchContent_Populate(<name>)with the same<name>more than once within a single CMake run. SeeFetchContent_GetProperties()for how to determine if population of a<name>has already been performed in the current run.
- FetchContent_GetProperties¶
When using saved content details, a call to
FetchContent_MakeAvailable()orFetchContent_Populate()records information in global properties which can be queried at any time. This information may include the source and binary directories associated with the content, and also whether or not the content population has been processed during the current configure run.FetchContent_GetProperties( <name> [SOURCE_DIR <srcDirVar>] [BINARY_DIR <binDirVar>] [POPULATED <doneVar>] )
The
SOURCE_DIR,BINARY_DIR, andPOPULATEDoptions can be used to specify which properties should be retrieved. Each option accepts a value which is the name of the variable in which to store that property. Most of the time though, only<name>is given, in which case the call will then set the same variables as a call toFetchContent_MakeAvailable(name)orFetchContent_Populate(name). Note that theSOURCE_DIRandBINARY_DIRvalues can be empty if the call is fulfilled by a dependency provider.This command is rarely needed when using
FetchContent_MakeAvailable(). It is more commonly used as part of implementing the deprecated pattern withFetchContent_Populate(), which ensures that the relevant variables will always be defined regardless of whether or not the population has been performed elsewhere in the project already:# WARNING: This pattern is deprecated, don't use it! # # Check if population has already been performed FetchContent_GetProperties(depname) if(NOT depname_POPULATED) # Fetch the content using previously declared details FetchContent_Populate(depname) # Set custom variables, policies, etc. # ... # Bring the populated content into the build add_subdirectory(${depname_SOURCE_DIR} ${depname_BINARY_DIR}) endif()
- FetchContent_SetPopulated¶
在 3.24 版被加入.
備註
This command should only be called by dependency providers. Calling it in any other context is unsupported and future CMake versions may halt with a fatal error in such cases.
FetchContent_SetPopulated( <name> [SOURCE_DIR <srcDir>] [BINARY_DIR <binDir>] )
If a provider command fulfills a
FETCHCONTENT_MAKEAVAILABLE_SERIALrequest, it must call this function before returning. TheSOURCE_DIRandBINARY_DIRarguments can be used to specify the values thatFetchContent_GetProperties()should return for its corresponding arguments. Only provideSOURCE_DIRandBINARY_DIRif they have the same meaning as if they had been populated by the built-inFetchContent_MakeAvailable()implementation.
變數¶
A number of cache variables can influence the behavior where details from a
FetchContent_Declare() call are used to populate content.
備註
All of these variables are intended for the developer to customize behavior. They should not normally be set by the project.
- FETCHCONTENT_BASE_DIR¶
In most cases, the saved details do not specify any options relating to the directories to use for the internal sub-build, final source, and build areas. It is generally best to leave these decisions up to the
FetchContentmodule to handle on the project's behalf. TheFETCHCONTENT_BASE_DIRcache variable controls the point under which all content population directories are collected, but in most cases, developers would not need to change this. The default location is${CMAKE_BINARY_DIR}/_deps, but if developers change this value, they should aim to keep the path short and just below the top level of the build tree to avoid running into path length problems on Windows.
- FETCHCONTENT_QUIET¶
The logging output during population can be quite verbose, making the configure stage quite noisy. This cache option (
ONby default) hides all population output unless an error is encountered. If experiencing problems with hung downloads, temporarily switching this option off may help diagnose which content population is causing the issue.在 3.30 版的變更:
FETCHCONTENT_QUIETis ignored if policyCMP0168is set toNEW. The output is still quiet by default in that case, but verbosity is controlled by the message logging level (seeCMAKE_MESSAGE_LOG_LEVELand--log-level).
- FETCHCONTENT_FULLY_DISCONNECTED¶
When this option is enabled, no attempt is made to download or update any content. It is assumed that all content has already been populated in a previous run, or the source directories have been pointed at existing contents the developer has provided manually (using options described further below). When the developer knows that no changes have been made to any content details, turning this option
ONcan speed up the configure stage. It isOFFby default.備註
The
FETCHCONTENT_FULLY_DISCONNECTEDvariable is not an appropriate way to prevent any network access on the first run in a build directory. Doing so can break projects, lead to misleading error messages, and hide subtle population failures. This variable is specifically intended to only be turned on after the first time CMake has been run. If you want to prevent network access even on the first run, use a dependency provider and populate the dependency from local content instead.在 3.30 版的變更: The constraint that the source directory has already been populated when
FETCHCONTENT_FULLY_DISCONNECTEDis true is now enforced. See policyCMP0170.
- FETCHCONTENT_UPDATES_DISCONNECTED¶
This is a less severe download/update control compared to
FETCHCONTENT_FULLY_DISCONNECTED. Instead of bypassing all download and update logic,FETCHCONTENT_UPDATES_DISCONNECTEDonly prevents the update step from making connections to remote servers when using the git or hg download methods. Updates still occur if details about the update step change, but the update is attempted with only the information already available locally (so switching to a different tag or commit that is already fetched locally will succeed, but switching to an unknown commit hash will fail). The download step is not affected, so if content has not been downloaded previously, it will still be downloaded when this option is enabled. This can speed up the configure step, but not as much asFETCHCONTENT_FULLY_DISCONNECTED.FETCHCONTENT_UPDATES_DISCONNECTEDisOFFby default.
- FETCHCONTENT_TRY_FIND_PACKAGE_MODE¶
在 3.24 版被加入.
This variable modifies the details that
FetchContent_Declare()records for a given dependency. While it ultimately controls the behavior ofFetchContent_MakeAvailable(), it is the variable's value whenFetchContent_Declare()is called that gets used. It makes no difference what the variable is set to whenFetchContent_MakeAvailable()is called. Since the variable should only be set by the user and not by projects directly, it will typically have the same value throughout anyway, so this distinction is not usually noticeable.FETCHCONTENT_TRY_FIND_PACKAGE_MODEultimately controls whetherFetchContent_MakeAvailable()is allowed to callfind_package()to satisfy a dependency. The variable can be set to one of the following values:OPT_INFetchContent_MakeAvailable()will only callfind_package()if theFetchContent_Declare()call included aFIND_PACKAGE_ARGSkeyword. This is also the default behavior ifFETCHCONTENT_TRY_FIND_PACKAGE_MODEis not set.ALWAYSfind_package()can be called byFetchContent_MakeAvailable()regardless of whether theFetchContent_Declare()call included aFIND_PACKAGE_ARGSkeyword or not. If noFIND_PACKAGE_ARGSkeyword was given, the behavior will be as thoughFIND_PACKAGE_ARGShad been provided, with no additional arguments after it.NEVERFetchContent_MakeAvailable()will not callfind_package(). AnyFIND_PACKAGE_ARGSgiven to theFetchContent_Declare()call will be ignored.
As a special case, if the
FETCHCONTENT_SOURCE_DIR_<uppercaseName>variable has a non-empty value for a dependency, it is assumed that the user is overriding all other methods of making that dependency available.FETCHCONTENT_TRY_FIND_PACKAGE_MODEwill have no effect on that dependency andFetchContent_MakeAvailable()will not try to callfind_package()for it.
In addition to the above, the following variables are also defined for each content name:
- FETCHCONTENT_SOURCE_DIR_<uppercaseName>¶
If this is set, no download or update steps are performed for the specified content and the
<lowercaseName>_SOURCE_DIRvariable returned to the caller is pointed at this location. This gives developers a way to have a separate checkout of the content that they can modify freely without interference from the build. The build simply uses that existing source, but it still defines<lowercaseName>_BINARY_DIRto point inside its own build area. Developers are strongly encouraged to use this mechanism rather than editing the sources populated in the default location, as changes to sources in the default location can be lost when content population details are changed by the project.
- FETCHCONTENT_UPDATES_DISCONNECTED_<uppercaseName>¶
This is the per-content equivalent of
FETCHCONTENT_UPDATES_DISCONNECTED. If the global option or this option isON, then updates for the git and hg methods will not contact any remote for the named content. They will only use information already available locally. Disabling updates for individual content can be useful for content whose details rarely change, while still leaving other frequently changing content with updates enabled.
範例¶
Typical Case¶
This first fairly straightforward example ensures that some popular testing frameworks are available to the main build:
include(FetchContent)
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
)
FetchContent_Declare(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG 605a34765aa5d5ecbf476b4598a862ada971b0cc # v3.0.1
)
# After the following call, the CMake targets defined by googletest and
# Catch2 will be available to the rest of the build
FetchContent_MakeAvailable(googletest Catch2)
Integrating With find_package()¶
For the previous example, if the user wanted to try to find googletest
and Catch2 via find_package() first before trying to download
and build them from source, they could set the
FETCHCONTENT_TRY_FIND_PACKAGE_MODE variable to ALWAYS.
This would also affect any other calls to FetchContent_Declare()
throughout the project, which might not be acceptable. The behavior can be
enabled for just these two dependencies instead by adding FIND_PACKAGE_ARGS
to the declared details and leaving
FETCHCONTENT_TRY_FIND_PACKAGE_MODE unset, or set to OPT_IN:
include(FetchContent)
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
FIND_PACKAGE_ARGS NAMES GTest
)
FetchContent_Declare(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG 605a34765aa5d5ecbf476b4598a862ada971b0cc # v3.0.1
FIND_PACKAGE_ARGS
)
# This will try calling find_package() first for both dependencies
FetchContent_MakeAvailable(googletest Catch2)
For Catch2, no additional arguments to find_package() are needed,
so no additional arguments are provided after the FIND_PACKAGE_ARGS
keyword. For googletest, its package is more commonly called GTest,
so arguments are added to support it being found by that name.
If the user wanted to disable FetchContent_MakeAvailable() from
calling find_package() for any dependency, even if it provided
FIND_PACKAGE_ARGS in its declared details, they could set
FETCHCONTENT_TRY_FIND_PACKAGE_MODE to NEVER.
If the project wanted to indicate that these two dependencies should be
downloaded and built from source and that find_package() calls
should be redirected to use the built dependencies, the
OVERRIDE_FIND_PACKAGE option should be used when declaring the content
details:
include(FetchContent)
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG 703bd9caab50b139428cea1aaff9974ebee5742e # release-1.10.0
OVERRIDE_FIND_PACKAGE
)
FetchContent_Declare(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG 605a34765aa5d5ecbf476b4598a862ada971b0cc # v3.0.1
OVERRIDE_FIND_PACKAGE
)
# The following will automatically forward through to FetchContent_MakeAvailable()
find_package(googletest)
find_package(Catch2)
CMake provides a FindGTest module which defines some variables that older
projects may use instead of linking to the imported targets. To support
those cases, we can provide an extra file. In keeping with the
"first to define, wins" philosophy of FetchContent, we only write out
that file if something else hasn't already done so.
FetchContent_MakeAvailable(googletest)
if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-extra.cmake AND
NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletestExtra.cmake)
file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-extra.cmake
[=[
if("${GTEST_LIBRARIES}" STREQUAL "" AND TARGET GTest::gtest)
set(GTEST_LIBRARIES GTest::gtest)
endif()
if("${GTEST_MAIN_LIBRARIES}" STREQUAL "" AND TARGET GTest::gtest_main)
set(GTEST_MAIN_LIBRARIES GTest::gtest_main)
endif()
if("${GTEST_BOTH_LIBRARIES}" STREQUAL "")
set(GTEST_BOTH_LIBRARIES ${GTEST_LIBRARIES} ${GTEST_MAIN_LIBRARIES})
endif()
]=])
endif()
Projects will also likely be using find_package(GTest) rather than
find_package(googletest), but it is possible to make use of the
CMAKE_FIND_PACKAGE_REDIRECTS_DIR area to pull in the latter as
a dependency of the former. This is likely to be sufficient to satisfy
a typical find_package(GTest) call.
FetchContent_MakeAvailable(googletest)
if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake AND
NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfig.cmake)
file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config.cmake
[=[
include(CMakeFindDependencyMacro)
find_dependency(googletest)
]=])
endif()
if(NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config-version.cmake AND
NOT EXISTS ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/GTestConfigVersion.cmake)
file(WRITE ${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/gtest-config-version.cmake
[=[
include(${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletest-config-version.cmake OPTIONAL)
if(NOT PACKAGE_VERSION_COMPATIBLE)
include(${CMAKE_FIND_PACKAGE_REDIRECTS_DIR}/googletestConfigVersion.cmake OPTIONAL)
endif()
]=])
endif()
Overriding Where To Find CMakeLists.txt¶
If the sub-project's CMakeLists.txt file is not at the top level of its
source tree, the SOURCE_SUBDIR option can be used to tell FetchContent
where to find it. The following example shows how to use that option, and
it also sets a variable which is meaningful to the subproject before pulling
it into the main build (set as an INTERNAL cache variable to avoid
problems with policy CMP0077):
include(FetchContent)
FetchContent_Declare(
protobuf
GIT_REPOSITORY https://github.com/protocolbuffers/protobuf.git
GIT_TAG ae50d9b9902526efd6c7a1907d09739f959c6297 # v3.15.0
SOURCE_SUBDIR cmake
)
set(protobuf_BUILD_TESTS OFF CACHE INTERNAL "")
FetchContent_MakeAvailable(protobuf)
Complex Dependency Hierarchies¶
In more complex project hierarchies, the dependency relationships can be more
complicated. Consider a hierarchy where projA is the top level project and
it depends directly on projects projB and projC. Both projB and
projC can be built standalone and they also both depend on another project
projD. projB additionally depends on projE. This example assumes
that all five projects are available on a company git server. The
CMakeLists.txt of each project might have sections like the following:
include(FetchContent)
FetchContent_Declare(
projB
GIT_REPOSITORY git@mycompany.com:git/projB.git
GIT_TAG 4a89dc7e24ff212a7b5167bef7ab079d
)
FetchContent_Declare(
projC
GIT_REPOSITORY git@mycompany.com:git/projC.git
GIT_TAG 4ad4016bd1d8d5412d135cf8ceea1bb9
)
FetchContent_Declare(
projD
GIT_REPOSITORY git@mycompany.com:git/projD.git
GIT_TAG origin/integrationBranch
)
FetchContent_Declare(
projE
GIT_REPOSITORY git@mycompany.com:git/projE.git
GIT_TAG v2.3-rc1
)
# Order is important, see notes in the discussion further below
FetchContent_MakeAvailable(projD projB projC)
include(FetchContent)
FetchContent_Declare(
projD
GIT_REPOSITORY git@mycompany.com:git/projD.git
GIT_TAG 20b415f9034bbd2a2e8216e9a5c9e632
)
FetchContent_Declare(
projE
GIT_REPOSITORY git@mycompany.com:git/projE.git
GIT_TAG 68e20f674a48be38d60e129f600faf7d
)
FetchContent_MakeAvailable(projD projE)
include(FetchContent)
FetchContent_Declare(
projD
GIT_REPOSITORY git@mycompany.com:git/projD.git
GIT_TAG 7d9a17ad2c962aa13e2fbb8043fb6b8a
)
FetchContent_MakeAvailable(projD)
A few key points should be noted in the above:
projBandprojCdefine different content details forprojD, butprojAalso defines a set of content details forprojD. BecauseprojAwill define them first, the details fromprojBandprojCwill not be used. The override details defined byprojAare not required to match either of those fromprojBorprojC, but it is up to the higher level project to ensure that the details it does define still make sense for the child projects.In the
projAcall toFetchContent_MakeAvailable(),projDis listed ahead ofprojBandprojC, so it will be populated before eitherprojBorprojC. It isn't required forprojAto do this, doing so ensures thatprojAfully controls the environment in whichprojDis brought into the build (directory properties are particularly relevant).While
projAdefines content details forprojE, it does not need to explicitly callFetchContent_MakeAvailable(projE)orFetchContent_Populate(projD)itself. Instead, it leaves that to the childprojB. For higher level projects, it is often enough to just define the override content details and leave the actual population to the child projects. This saves repeating the same thing at each level of the project hierarchy unnecessarily, but it should only be done if directory properties set by dependencies are not expected to influence the population of the shared dependency (projEin this case).
Populating Content Without Adding It To The Build¶
Projects don't always need to add the populated content to the build. Sometimes the project just wants to make the downloaded content available at a predictable location. The next example ensures that a set of standard company toolchain files (and potentially even the toolchain binaries themselves) is available early enough to be used for that same build.
cmake_minimum_required(VERSION 3.14)
include(FetchContent)
FetchContent_Declare(
mycom_toolchains
URL https://intranet.mycompany.com//toolchains_1.3.2.tar.gz
)
FetchContent_MakeAvailable(mycom_toolchains)
project(CrossCompileExample)
The project could be configured to use one of the downloaded toolchains like so:
cmake -DCMAKE_TOOLCHAIN_FILE=_deps/mycom_toolchains-src/toolchain_arm.cmake /path/to/src
When CMake processes the CMakeLists.txt file, it will download and unpack
the tarball into _deps/mycompany_toolchains-src relative to the build
directory. The CMAKE_TOOLCHAIN_FILE variable is not used until
the project() command is reached, at which point CMake looks for the
named toolchain file relative to the build directory. Because the tarball has
already been downloaded and unpacked by then, the toolchain file will be in
place, even the very first time that cmake is run in the build directory.
Populating Content In CMake Script Mode¶
This last example demonstrates how one might download and unpack a
firmware tarball using CMake's script mode.
The call to FetchContent_Populate() specifies all the content details
and the unpacked firmware will be placed in a firmware directory below the
current working directory.
getFirmware.cmake¶# NOTE: Intended to be run in script mode with cmake -P
include(FetchContent)
FetchContent_Populate(
firmware
URL https://mycompany.com/assets/firmware-1.23-arm.tar.gz
URL_HASH MD5=68247684da89b608d466253762b0ff11
SOURCE_DIR firmware
)