The FetchContent module enables populating content at configure time, via any method supported by the ExternalProject module, and has become a standard part of CMake in its 3.11 version. Whereas ExternalProject_Add() downloads at build time (as seen in Chapter 8, The Superbuild Pattern), the FetchContent module makes content available immediately, such that the main project and the fetched external project (in this case, the Google Test) can be processed when CMake is first invoked, and can be nested using add_subdirectory.
To fetch Google Test sources, we have first declared the external content:
include(FetchContent)
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-1.8.0
)
In this case, we fetched a Git repository with a specific tag (release-1.8.0), but we could also fetch an external project from a Subversion, Mercurial, or HTTP(S) source. For available options, consult the options of the corresponding ExternalProject_Add command at https://cmake.org/cmake/help/v3.11/module/ExternalProject.html.
We checked whether content population was already processed with the FetchContent_GetProperties() command, before calling FetchContent_Populate(); otherwise, FetchContent_Populate() would have thrown an error if it was called more than once.
The command FetchContent_Populate(googletest) populates the sources and defines googletest_SOURCE_DIR and googletest_BINARY_DIR, which we can use to process the Google Test project (using add_subdirectory(), since it happens to be a CMake project, as well):
add_subdirectory(
${googletest_SOURCE_DIR}
${googletest_BINARY_DIR}
)
The preceding defines the following targets: gtest, gtest_main, gmock, and gmock_main. In this recipe, we were only interested in the gtest_main target, as a library dependency for the unit test example:
target_link_libraries(cpp_test
PRIVATE
sum_integers
gtest_main
)
When building our code, we can see how it correctly triggers the configure and build steps for Google Test. One day, we will wish to upgrade to a later Google Test release, and the only line that we will probably need to change is the one detailing the GIT_TAG.