Relative including cmake scripts in a subproject


I have the following problem: I’m fetching and building a few dependencies that should ship with my applications, primarily header-only and static libraries. I’m using FetchContent for that and it has been working great so far.

However, the new project has the following include in their CMake:


and it is used to include cmake/dependencies.cmake.
Unfortunately, my project uses exactly the same structure, and for some reason, this resolves to a recursive inclusion of my file.

Is there a flag or option that I might have forgotten to set? I haven’t found anything in the documentation on include function. At the moment, I resolved it by replacing the line in the dependency with


but it’s not a long-term solution. Ideally, I’d like to make sure that all CMake configuration in the dependency uses path relative to <build-dir>/_deps/<dependency>-src.

My fetching script:

# AWS SDK - just the S3 part.                                                                       
 find_package(AWSSDK COMPONENTS s3 QUIET)                                                            
  if(NOT AWSSDK_FOUND)                                                                                
    message(STATUS "Downloading and building AWS SDK dependency")                                     
   set(BUILD_ONLY "s3" CACHE INTERNAL "")                                                            
   set(ENABLE_TESTING OFF CACHE INTERNAL "")                                                         
   add_subdirectory(${awssdk_SOURCE_DIR} ${awssdk_BINARY_DIR})                                       

Projects should add their local CMake script directories to the front of CMAKE_MODULE_PATH, not the end. The AWS SDK project will need to use list(INSERT CMAKE_MODULE_PATH 0) instead of list(APPEND) (or something similar).

Why do you call add_subdirectory() here? This is already something that FetchContent_MakeAvailable() does, so you will be including the same source directory with the same binary directory twice. I’m somewhat surprised CMake doesn’t complain about that.

Actually this whole block is a bit of a muddle. Don’t call FetchContent_Populate() if you’re using FetchContent_MakeAvailable(). And setting the variables as cache variables also looks suspicious (sometimes you might need to do that, but I’d normally set non-cache variables for local changes like this unless the dependency requires them to be cache variables). I’d expect this block to look something more like this:

   set(BUILD_ONLY "s3")