1
0
mirror of synced 2024-11-05 20:48:56 +01:00
modern-cmake/chapters/projects/fetch.md

53 lines
1.7 KiB
Markdown
Raw Normal View History

2019-08-07 07:06:55 +02:00
# FetchContent (CMake 3.11+)
2018-03-29 19:30:00 +02:00
2018-03-30 15:39:25 +02:00
Often, you would like to do your download of data or packages as part of the configure instead of the build. This was invented several times in third party modules, but was finally added to CMake itself as part of CMake 3.11 as the [FetchContent] module.
The [FetchContent] module has excellent documentation that I won't try to repeat. The key ideas are:
2019-08-23 12:23:08 +02:00
* Use `FetchContent_Declare(MyName)` to get data or a package. You can set URLs, Git repositories, and more.
2018-03-30 15:39:25 +02:00
* Use `FetchContent_GetProperties(MyName)` on the name you picked in the first step to get `MyName_*` variables.
2019-03-07 22:09:38 +01:00
* Check `MyName_POPULATED`, and if not populated, use `FetchContent_Populate(MyName)` (and if a package, `add_subdirectory("${MyName_SOURCE_DIR}" "${MyName_BINARY_DIR}")`)
2018-03-30 15:39:25 +02:00
2018-04-05 13:01:02 +02:00
For example, to download Catch2:
```cmake
FetchContent_Declare(
catch
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
2019-08-07 07:06:55 +02:00
GIT_TAG v2.9.1
2018-04-05 13:01:02 +02:00
)
2019-08-07 07:06:55 +02:00
# CMake 3.14+
2019-11-09 06:15:09 +01:00
FetchContent_MakeAvailable(catch)
2019-08-07 07:06:55 +02:00
```
If you can't use CMake 3.14+, the classic way to prepare code was:
```cmake
# CMake 3.11+
2018-04-05 13:01:02 +02:00
FetchContent_GetProperties(catch)
if(NOT catch_POPULATED)
FetchContent_Populate(catch)
add_subdirectory(${catch_SOURCE_DIR} ${catch_BINARY_DIR})
endif()
```
2019-08-07 07:06:55 +02:00
Of course, you could bundled this up into a macro:
```cmake
if(${CMAKE_VERSION} VERSION_LESS 3.14)
macro(FetchContent_MakeAvailable NAME)
FetchContent_GetProperties(${NAME})
if(NOT ${NAME}_POPULATED)
FetchContent_Populate(${NAME})
add_subdirectory(${${NAME}_SOURCE_DIR} ${${NAME}_BINARY_DIR})
endif()
endmacro()
endif()
```
Now you have the CMake 3.14+ syntax in CMake 3.11+.
2018-03-30 15:39:25 +02:00
[FetchContent]: https://cmake.org/cmake/help/latest/module/FetchContent.html