cmakecmake-language

How can I make a variable set by an external project added with add_subdirectory available to the scope that did add_subdirectory?


I have two separate git projects that I build using cmake.

Project_A
    |CMakeLists_A.txt
    |foo.H

In the CMakeLists_A.txt file, I define a variable that points to foo.H as follows:

set(var_projectA ${CMAKE_CURRENT_SOURCE_DIR}/foo.H)

I add Project A as a subdirectory in Project B, which has the following structure:

Project B
    |CMakeLists_B.txt
    |Subdirectory_B
        |CMakeLists_subB.txt
        |test.cpp

In CMakeLists_B.txt, I have:

add_subdirectory(${CMAKE_SOURCE_DIR}/extern/Project_A)

How can I access the variable var_projectA in the subdirectory of Project B (i.e., in CMakeLists_subB.txt)?


Solution

  • Variables in CMake are directory, function, and block scoped. add_subdirectory creates a new directory "child scope". You can set a variable in the parent scope of a given scope by using the PARENT_SCOPE argument of the set command.

    Note that if you want a variable to be set at a given scope and the parent scope, you need to call set twice- once to set it at that scope, and once to set it at its parent scope.

    If a parent directory scope isn't guaranteed to exist, you can check that CMAKE_SOURCE_DIR is not equal to the CMAKE_CURRENT_SOURCE_DIR, like so:

    if(NOT ("${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}"))
      set(foo "hello world!" PARENT_SCOPE)
    endif()