Using FetchContent Modules

Let's learn about how to import and use FetchContent.

Nowadays, it is recommended to go with the FetchContent module to import external projects. This module has been available in CMake since version 3.11, but we recommend using at least 3.14 to work with it effectively.

The FetchContent module

Essentially, it's a high-level wrapper around ExternalProject, offering similar functionality and more. The key difference is in the stage of execution—unlike ExternalProject, FetchContent populates dependencies during the configuration stage, bringing all the targets declared by an external project to the scope of the main project. This way, we can use them exactly like the ones we defined ourselves.

The usage of FetchContent module requires three steps:

  1. Include the module in our project with include(FetchModule).

  2. Configure dependencies with the FetchContent_Declare() command.

  3. Populate dependencies with the FetchContent_MakeAvailable() command—download, build, install, and add its list files to the main project and parse.

We may ask ourselves why the Declare and MakeAvailable commands were separated. This was done to enable configuration overrides in hierarchical projects. Here's a scenario: a parent project depends on the A and B external libraries. The A library also depends on B, but the authors of the A library are still using an old version, different from the parent project, shown in the following figure:

Get hands-on with 1400+ tech skills courses.