如何在cmake函数中设置全局变量? [英] How to set the global variable in a function for cmake?
问题描述
我正在编写CMakeLists.txt以生成文件并编译生成的文件。我创建了一个向全局列表变量添加一些文件路径字符串的函数。
I'm writing a CMakeLists.txt to generate files and compile the generated files. I create a function to add some file path strings to a global list variable.
我的CMakeLists.txt:
My CMakeLists.txt:
set(source_list "nothing")
function(test file_path)
list(APPEND source_list ${file_path})
endfunction(test)
test(abc.txt)
test(def.txt)
message("At last, the source_list is:\"${source_list}\"")
cmake输出:
At last, the source_list is:"nothing"
有人建议使用宏而不是函数,但是我确实需要使用局部变量,因此需要使用函数而不是宏。
Someone suggested that to use macro instead of function, but I do need use local variable, so I need to use the function instead of macro.
如何正确地在函数test()中设置全局变量source_list?不能以简单和正常的方式进行操作吗?
How can I correctly set the global variable source_list in the function test()? Can't cmake do it in a simple and normal way?
推荐答案
您需要使用 set
而不是 list
会影响父作用域中的变量。
You need to use set
instead of list
to affect the variable in the parent scope.
因此,请替换 list
命令,其中:
So replace your list
command with:
set(source_list ${source_list} ${file_path} PARENT_SCOPE)
这篇关于如何在cmake函数中设置全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!