英文:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论