在宏范围内设置CMake宏参数

Pat*_* B. 3 cmake

cmake-macro的参数是否在宏的范围内和期间是只读的?

请考虑以下代码:

macro(test arg)
    message("output: ${arg}")
    set(arg "overwritten")
    message("output: ${arg}")
endmacro(test)

test("original")
Run Code Online (Sandbox Code Playgroud)

输出是

output: original
output: original
Run Code Online (Sandbox Code Playgroud)

有没有办法改变这种行为?

Com*_*sMS 6

改为使用函数:

function(test arg)
    message("output: ${arg}")
    set(arg "overwritten")
    message("output: ${arg}")
endfunction(test)
Run Code Online (Sandbox Code Playgroud)

来自CMake docs on macro:

请注意,宏的参数和ARGN等值不是通常的CMake意义上的变量.它们是字符串替换,就像c预处理器与宏一样.如果你想要真正的CMake变量,你应该看一下function命令.

Keep in mind though that unlike macros, functions introduce a new scope. So whenever you set a variable in a function, you have to give PARENT_SCOPE as a parameter to make the change visible to the caller.