gpt4 book ai didi

cmake - 如何在 CMake 的 execute_process 中传递列表变量?

转载 作者:行者123 更新时间:2023-12-04 01:52:42 24 4
gpt4 key购买 nike

我想在 execute_process 的子目录中执行 CMake 命令,并将一些缓存变量作为 -D 传递选项。

如果变量是字符串类型,它就可以工作。但是,如果变量是列表,则 typical method在命令行中传递列表似乎不起作用。

我尝试了该答案中列出的所有组合。我什至尝试加入 mylist"\\;""\\\\;" .然而,execute_process似乎总是打开 '-DVal2=a\\;b\\;c\\;''-DVal2=a;b;c'-Dval2=a b c .

我怎样才能防止这种情况?只有 -DVal2=a\\;b\\;c有效,但很烦人。

set(
mylist
a
b
c
)

set(
cmake_args
"-DVal1=abc"
"'-DVal2=${mylist}'" #does not work, the execute_process will unpack it into seperated args
)

execute_process(
COMMAND ${CMAKE_COMMAND} ${cmake_args} ${CMAKE_SOURCE_DIR}/subproject
OUTPUT_FILE ${CMAKE_BINARY_DIR}/config.log
ERROR_FILE ${CMAKE_BINARY_DIR}/config.log
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/subproject
RESULT_VARIABLE config_result
)

最佳答案

在传递列表之前,在其上运行以下行:

string(REPLACE ";" "\\;" escaped_list "${my_list}")

然后通过escaped_list。在另一端,它将有
与 my_list 完全相同的值。

例如,
set(my_list "a\;b" "c" "d")
string(REPLACE ";" "\\;" escaped_list "${my_list}")
execute_process(COMMAND ${CMAKE_COMMAND} -Dmy_list=${escaped_list} -P test.cmake)

(用 cmake 3.17 测试)。

这也适用于首先分配给 cmake_args 的情况。并通过。
例如,

test1.cmake
# Construction.
set(my_list "a\;b" "c" "d")
set(other_list "e" "f\;g" "h")

# For debugging purposes.
message("my_list = \"${my_list}\".")
foreach(arg ${my_list})
message("-> ${arg}")
endforeach()
message("other_list = \"${other_list}\".")
foreach(arg ${other_list})
message("-> ${arg}")
endforeach()

# Encoding.
string(REPLACE ";" "\\;" escaped_list "${my_list}")
message("escaped_list = \"${escaped_list}\".")

string(REPLACE ";" "\\;" other_escaped_list "${other_list}")
message("other_escaped_list = \"${other_escaped_list}\".")

set(cmake_args "-Dother_list=${other_escaped_list}" "-Dmy_list=${escaped_list}")

execute_process(
COMMAND
${CMAKE_COMMAND} ${cmake_args} -P test2.cmake
)

test2.cmake
# For debugging purpose.
message("my_list = \"${my_list}\".")
foreach(arg ${my_list})
message("-> ${arg}")
endforeach()

message("other_list = \"${other_list}\".")
foreach(arg ${other_list})
message("-> ${arg}")
endforeach()

运行输出 cmake -P test1.cmake :
my_list = "a\;b;c;d".
-> a;b
-> c
-> d
other_list = "e;f\;g;h".
-> e
-> f;g
-> h
escaped_list = "a\\;b\;c\;d".
other_escaped_list = "e\;f\\;g\;h".
my_list = "a\;b;c;d".
-> a;b
-> c
-> d
other_list = "e;f\;g;h".
-> e
-> f;g
-> h

请仔细观察使用和未使用双引号的位置。

关于cmake - 如何在 CMake 的 execute_process 中传递列表变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52206191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com