0

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)?

starball
  • 20,030
  • 7
  • 43
  • 238
Rob S
  • 27
  • 1
  • 7
  • The variable `var_projectA` is local to the script `extern/Project_A/CMakeLists.txt`. You cannot access it from `CMakeLists_subB.txt`. – Tsyvarev Apr 06 '23 at 21:42
  • Thanks for your comment @Tsyvarev So there's no way to access ```var_projectA``` in Project B? Is there a workaround I can use if I wanted to achieve this? – Rob S Apr 06 '23 at 21:50
  • If you are allowed to modify `extern/Project_A/CMakeLists.txt`, then instead of normal variable `var_projectA` you could define the one in PARENT_SCOPE, or the CACHE one, or use the global property. – Tsyvarev Apr 06 '23 at 22:31
  • Thanks @Tsyvarev, please see my comment below that also responds to your comment. – Rob S Apr 07 '23 at 13:01

1 Answers1

1

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()
starball
  • 20,030
  • 7
  • 43
  • 238