FetchContent (Offline)
find_package uses a library that is already installed. FetchContent takes the other route: it downloads a dependency's source at configure time and adds it to your build as if it were a subdirectory. Your targets then link the dependency's targets directly.
include(FetchContent)
FetchContent_Declare(fmt
GIT_REPOSITORY https://github.com/fmtlib/fmt.git
GIT_TAG 12.1.0) # a tag or, better, a full commit hash
FetchContent_MakeAvailable(fmt) # download (once) + add_subdirectory
target_link_libraries(app PRIVATE fmt::fmt)It's simple and needs nothing installed, which makes it popular for test frameworks and small libraries. The costs: every clean build directory downloads again, the dependency's CMake code becomes part of your build (its options, its warnings, its target names), and there is no binary caching. For many or large dependencies, a package manager is the better tool (C/C++ Packages covers Conan, vcpkg and CPM.cmake, a thin wrapper around FetchContent).
These sessions have no network
Every session in this course runs with networking switched off, so this is what a GitHub URL does here (the useful lines only):
mkdir -p app && cd app
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.30)
project(App LANGUAGES CXX)
include(FetchContent)
FetchContent_Declare(fmt GIT_REPOSITORY https://github.com/fmtlib/fmt.git GIT_TAG 12.1.0)
FetchContent_MakeAvailable(fmt)
CM
cmake -S . -B build -G Ninja --log-level=NOTICE 2>&1 | grep -E 'fatal|Had to|Failed|incomplete' | awk '!seen[$0]++'fatal: unable to access 'https://github.com/fmtlib/fmt.git/': Could not resolve host: github.com
Had to git clone more than once: 3 times.
Failed to clone repository:
-- Configuring incomplete, errors occurred!
Git tried three times, then the configure failed. This is also what happens on a CI machine without internet access, or when GitHub is down, which is a good reason to know the offline techniques below. They are real features, not workarounds.
Fetching from a local git repository
GIT_REPOSITORY accepts any URL git understands, including a local path. This session creates a small header-only library as a git repository with a tag, then fetches it:
# --- the dependency: a git repo with a tag
mkdir -p mathlib/include && cd mathlib
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(MathLib VERSION 1.0.0 LANGUAGES CXX)
add_library(mathlib INTERFACE)
add_library(MathLib::mathlib ALIAS mathlib)
target_include_directories(mathlib INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include)
CM
echo 'inline int square(int x) { return x * x; }' > include/mathlib.hpp
git init -q && git add . && git commit -q -m "mathlib 1.0" && git tag v1.0.0
# --- the consumer
mkdir -p ~/app && cd ~/app
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.30)
project(App LANGUAGES CXX)
include(FetchContent)
FetchContent_Declare(mathlib
GIT_REPOSITORY ${CMAKE_CURRENT_SOURCE_DIR}/../mathlib
GIT_TAG v1.0.0)
FetchContent_MakeAvailable(mathlib)
message("mathlib source dir: ${mathlib_SOURCE_DIR}")
add_executable(app main.cpp)
target_link_libraries(app PRIVATE MathLib::mathlib)
CM
cat > main.cpp <<'SRC'
#include <cstdio>
#include <mathlib.hpp>
int main() { std::printf("square(7) = %d\n", square(7)); }
SRC
cmake -S . -B build -G Ninja --log-level=NOTICE
cmake --build build && ./build/app
ls build/_deps
git -C build/_deps/mathlib-src describe --tagsCloning into 'mathlib-src'...
done.
HEAD is now at f4f1786 mathlib 1.0
mathlib source dir: /home/learner/app/build/_deps/mathlib-src
-- Configuring done (0.3s)
-- Generating done (0.0s)
-- Build files have been written to: /home/learner/app/build
[1/2] Building CXX object CMakeFiles/app.dir/main.cpp.o
[2/2] Linking CXX executable app
square(7) = 49
mathlib-build
mathlib-src
mathlib-tmp
v1.0.0
The dependency's sources were cloned into build/_deps/mathlib-src (its build files go in mathlib-build), and FetchContent_MakeAvailable defined mathlib_SOURCE_DIR and mathlib_BINARY_DIR. Note the lower-case name: FetchContent always lower-cases the name you declare for these variables.
Note: With
cmake_minimum_required(VERSION 3.30)or later (policy CMP0168), FetchContent downloads directly. Older policy settings run a hidden sub-build (anExternalProjectin_deps/<name>-subbuild) for every dependency, which is noticeably slower. That is one more reason to keep your minimum version current.
Overriding the source: FETCHCONTENT_SOURCE_DIR_
To build against a local checkout instead (you are fixing a bug in the dependency, or your CI has a mirror), set FETCHCONTENT_SOURCE_DIR_<UPPERCASE NAME>. FetchContent then skips the download entirely and uses that directory. No CMake code changes:
mkdir -p mathlib-dev/include && cd mathlib-dev
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(MathLib VERSION 1.1.0 LANGUAGES CXX)
add_library(mathlib INTERFACE)
add_library(MathLib::mathlib ALIAS mathlib)
target_include_directories(mathlib INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include)
CM
echo 'inline int square(int x) { return x * x + 0; } // 1.1 work in progress' > include/mathlib.hpp
mkdir -p ~/app && cd ~/app
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.30)
project(App LANGUAGES CXX)
include(FetchContent)
FetchContent_Declare(mathlib
GIT_REPOSITORY https://git.example.com/mathlib.git # never contacted
GIT_TAG v1.0.0)
FetchContent_MakeAvailable(mathlib)
message("mathlib from ${mathlib_SOURCE_DIR}")
CM
cmake -S . -B build -G Ninja --log-level=NOTICE -DFETCHCONTENT_SOURCE_DIR_MATHLIB=$HOME/mathlib-devmathlib from /home/learner/mathlib-dev
-- Configuring done (0.2s)
-- Generating done (0.0s)
-- Build files have been written to: /home/learner/app/build
The URL points at a server that doesn't exist, and nothing tried to contact it.
Fetching an archive with a hash
URL downloads an archive (.tar.gz, .zip) and unpacks it. Always add URL_HASH, so a changed or tampered archive fails the build instead of being used. A file:// URL works offline:
mkdir -p mathlib/include
cat > mathlib/CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(MathLib VERSION 1.0.0 LANGUAGES CXX)
add_library(mathlib INTERFACE)
add_library(MathLib::mathlib ALIAS mathlib)
target_include_directories(mathlib INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include)
CM
echo 'inline int square(int x) { return x * x; }' > mathlib/include/mathlib.hpp
# a reproducible archive: fixed order, owner and timestamps
tar --sort=name --mtime=@$SOURCE_DATE_EPOCH --owner=0 --group=0 --numeric-owner -cf - mathlib | gzip -n > mathlib-1.0.0.tar.gz
HASH=$(sha256sum mathlib-1.0.0.tar.gz | cut -d' ' -f1)
mkdir -p app && cd app
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.30)
project(App LANGUAGES CXX)
include(FetchContent)
FetchContent_Declare(mathlib
URL file://${CMAKE_CURRENT_SOURCE_DIR}/../mathlib-1.0.0.tar.gz
URL_HASH SHA256=${MATHLIB_SHA256})
FetchContent_MakeAvailable(mathlib)
message("unpacked to ${mathlib_SOURCE_DIR}")
CM
echo "--- correct hash"
cmake -S . -B build -G Ninja --log-level=NOTICE -DMATHLIB_SHA256=$HASH | grep -v '^--'
echo "--- wrong hash"
cmake -S . -B build-bad -G Ninja --log-level=NOTICE \
-DMATHLIB_SHA256=0000000000000000000000000000000000000000000000000000000000000000 2>&1 \
| sed -n '/error: SHA256/,/actual:/p'--- correct hash
unpacked to /home/learner/app/build/_deps/mathlib-src
--- wrong hash
error: SHA256 hash of
/home/learner/app/../mathlib-1.0.0.tar.gz
does not match expected value
expected: '0000000000000000000000000000000000000000000000000000000000000000'
actual: '5e86e74ea396d3bb98ac9df66ea7a3ab3e2a733445c3186c5ca48cbb9ea12b8f'
Prefer an installed copy: FIND_PACKAGE_ARGS
Since CMake 3.24, a declaration can say "use find_package first, fetch only if that fails". Distribution packagers love this, because they can build your project against the system libraries without patching it:
FetchContent_Declare(fmt
GIT_REPOSITORY https://github.com/fmtlib/fmt.git
GIT_TAG 12.1.0
FIND_PACKAGE_ARGS 12 CONFIG) # try find_package(fmt 12 CONFIG) first
FetchContent_MakeAvailable(fmt)Setting -DFETCHCONTENT_TRY_FIND_PACKAGE_MODE=ALWAYS applies the same idea to every declaration, and NEVER turns it off.
Other cache variables worth knowing
| Variable | Effect |
|---|---|
FETCHCONTENT_FULLY_DISCONNECTED=ON |
never download or update; use what's already in _deps (fails if it's missing) |
FETCHCONTENT_UPDATES_DISCONNECTED=ON |
download once, but don't check for updates on re-configure |
FETCHCONTENT_BASE_DIR |
where _deps lives (share it between build directories to avoid re-downloading) |
FETCHCONTENT_QUIET=OFF |
show the download output |
Rules that keep FetchContent sane
- Pin
GIT_TAGto a commit hash for anything security-relevant; tags can be moved. - Declare all dependencies before making any available, at the top level, so the top-level project wins version conflicts (the first declaration of a name is the one used).
- Pass options to the dependency with
set(FMT_TEST OFF CACHE BOOL "" FORCE)beforeMakeAvailable, or useSYSTEM/EXCLUDE_FROM_ALLinFetchContent_Declare(3.25 / 3.28) to silence its warnings and keep its targets out ofall.
Test yourself
What does FetchContent_MakeAvailable(foo) do?
- Installs foo system-wide
- Downloads foo's source (if needed) and adds it to the build like add_subdirectory
- Runs find_package(foo)
- Builds foo in a separate process at build time
How do you build against a local checkout of a FetchContent dependency named mathlib without editing CMakeLists.txt?
- -DFETCHCONTENT_SOURCE_DIR_MATHLIB=/path/to/checkout
- -DCMAKE_PREFIX_PATH=/path
- -Dmathlib_DIR=/path
- -DFETCHCONTENT_BASE_DIR=/path
Why add URL_HASH to a URL download?
- It makes downloads faster
- A changed or tampered archive fails the build instead of silently being used
- It's required for zip files
- It enables caching across machines