CMake FetchContent does not copy libraries

I am using CMake FetchContent to download and build a third party library(realsense2 in this case). After trying out the googletest example from the official documentation (https://cmake.org/cmake/help/v3.11/module/FetchContent.html) I was impressed how easy it works. Including headers was done magically. Now with realsense2 SDK I have a problem.

I need to do add an additional include_directories command like this:

FetchContent_Declare(
realsense2
GIT_REPOSITORY https://github.com/IntelRealSense/librealsense.git
GIT_TAG        v2.23.0
)
FetchContent_MakeAvailable(realsense2)
FetchContent_GetProperties(realsense2)
if(NOT realsense2_POPULATED)
    FetchContent_Populate(realsense2)
    add_subdirectory(${realsense2_SOURCE_DIR} ${realsense2_BINARY_DIR})
endif()
//I should not be required to do this according to documentation
include_directories(${realsense2_SOURCE_DIR}/include)

If I do not do this, some headers are not found. Any suggestions regarding this problem?

EDIT: To clarify, this is how I added the libraries:

target_link_libraries(TestExe gtest gtest_main)

and the other exactly the same but this time it is not an exe its a dll

add_library(TestLib SHARED ${TestLib_HEADERS} ${TestLib_SOURCES} )
target_link_libraries(TestLib realsense2)

At this point I am more concerned about why I do not have to add any includes for googletest framework

Answer

The main purpose of FetchContent is a garantee that at the time of call

add_subdirectory(${Foo_SOURCE_DIR} ${Foo_BINARY_DIR})

the “fetched” project will be (as sources) in the ${Foo_SOURCE_DIR} directory.

How to use the project inluded via add_subdirectory is completely up to that project:

  1. Some projects (including gtest) create the library target Foo in a “modern” CMake way, by associating properties with it using target_include_directories and other commands. So, to use a library like this, it is sufficient to call target_link_libraries.

  2. Some other projects require both include_directories and target_link_libraries to work with them.

  3. Finally, there are many projects, which simply don’t work when included via add_subdirectory. So FetchContent makes little sense for them.

Only a small subset of projects describe how to work with them via add_subdirectory approach. And gtest is among them.

But most projects simply don’t describe this; if you want to use add_subdirectory with such a project, then you need to investigate the internals of that project to understand its usage (or use trial and error).

Leave a Reply

Your email address will not be published. Required fields are marked *