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

huangapple go评论61阅读模式
英文:

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

问题

如何在Project B的子目录中(即CMakeLists_subB.txt中)访问变量var_projectA?

英文:

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

答案1

得分: 1

在CMake中,变量是目录、函数和块作用域的add_subdirectory创建一个新的目录,“子作用域”。您可以使用set命令PARENT_SCOPE参数,在给定作用域的父作用域中设置变量。

请注意,如果您希望变量在给定作用域和其父作用域中都设置,您需要调用set两次:一次在该作用域设置它,一次在其父作用域设置它。

如果不确定父“目录作用域”是否存在,您可以检查CMAKE_SOURCE_DIR不等于CMAKE_CURRENT_SOURCE_DIR,如下所示:

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

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

huangapple
  • 本文由 发表于 2023年4月7日 05:21:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定