In this recipe, we will only focus on how to fetch the Google Test sources to build the gtest_main target. For a discussion on how this target is used to test the example sources, we refer the reader to Chapter 4, Creating and Running Tests, Recipe 3, Defining a unit test and linking against Google Test:
- We first include the FetchContent module, which will provide the functions that we will require to declare, query, and populate the dependency:
include(FetchContent)
- Then, we declare the content - its name, repository location, and the precise version to fetch:
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG release-1.8.0
)
- We then query whether the content has already been fetched/populated:
FetchContent_GetProperties(googletest)
- The previous function call defines googletest_POPULATED. If the content is not yet populated, we fetch the content and configure the subproject:
if(NOT googletest_POPULATED)
FetchContent_Populate(googletest)
# ...
# adds the targets: gtest, gtest_main, gmock, gmock_main
add_subdirectory(
${googletest_SOURCE_DIR}
${googletest_BINARY_DIR}
)
# ...
endif()
- Notice how the content is fetched at configure time:
$ mkdir -p build
$ cd build
$ cmake ..
- This generates the following build directory tree. The Google Test sources are now in place to be processed by CMake and provide the required target(s):
build/
├── ...
├── _deps
│ ├── googletest-build
│ │ ├── ...
│ │ └── ...
│ ├── googletest-src
│ │ ├── ...
│ │ └── ...
│ └── googletest-subbuild
│ ├── ...
│ └── ...
└── ...