Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

cmake

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?

like image 365
Daniel V. Avatar asked Jan 25 '26 07:01

Daniel V.


1 Answers

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

  • FetchContent_MakeAvailable: The simpler, and often preferred approach
  • FetchContent_GetProperties and FetchContent_Populate: An approach offering more precise control, allowing custom variables/policies

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)
like image 87
Kevin Avatar answered Jan 28 '26 00:01

Kevin