Daniel V.
Daniel V.

Reputation: 383

How to find the source directory of package downloaded via FetchContent?

I have multiple static libraries created in house that get linked into an image.

I want to use an external library that gets retrieved by using FetchContent_Declare.

proj
  /lib1
    CMakeList.txt
  /lib2
    CMakeList.txt
  /exe
    CMakeList.txt
  /external
    CMakeList.txt (FetchContent_Declare)
  /build
    /deps
      /externallib1 (auto generated)
  CMakeList.txt

I would like to use the following in /proj/CMakeList:

include_directories(externallib1/include)

But I don't know how to figure out the directory where the external library was actually downloaded?

Upvotes: 12

Views: 15078

Answers (1)

Kevin
Kevin

Reputation: 18253

The FetchContent module provides primary two approaches for populating the content of the external package in your main CMake build:

Whichever approach you use, the <lcname>_SOURCE_DIR variable for the package should be defined, which points to the top-level source directory of the download external package. In this case, <lcname> is the lower-case name of the package provided to one of the above commands.

CMake typically downloads the external package into your build directory here:

${CMAKE_BINARY_DIR}/_deps/<package-name>-src

but you can use the aforementioned <lcname>_SOURCE_DIR variable to reference this location.

For example, with googletest, one simple usage might look like this:

include(FetchContent)
FetchContent_Declare(
  googletest
  GIT_REPOSITORY https://github.com/google/googletest.git
  GIT_TAG        release-1.8.0
)
FetchContent_MakeAvailable(googletest)

Consequently, the googletest_SOURCE_DIR variable will point to the top-level source directory of the downloaded googletest repository, and you can include the googletest headers using something like the following:

include_directories(${googletest_SOURCE_DIR}/googletest/include/gtest)

Upvotes: 18

Related Questions