Escape “[]” characters in a semicolon-separated list in CMake

孤街浪徒 提交于 2021-02-07 11:52:53

问题


I found "[" and "]" might have special meanings in a semicolon-separated list in CMake. When I try this code in CMakeLists.txt:

set(XX "a" "b" "[" "]")
message("${XX}")

foreach(x ${XX})
        message("--> ${x}")
endforeach()

I expect the result:

a;b;[;]
--> a
--> b
--> [
--> ]

However I got this:

a;b;[;]
--> a
--> b
--> [;]

I didn't find any documentation for the usage of "[" and "]". Is it possible to escape these characters so that I can get the expected result? I am using CMake 2.8.12.2. Thanks for any help :)


回答1:


According to the documentation opening square bracket definitely has a special meaning:

Note: CMake versions prior to 3.0 do not support bracket arguments. They interpret the opening bracket as the start of an Unquoted Argument.

So the problem is mixing Quoted and Unquoted arguments. Possible workaround in your case is to replace opening square bracket to something else in initialization and later replace it back, like this:

CMAKE_MINIMUM_REQUIRED (VERSION 2.8.11)
PROJECT (HELLO NONE)

SET(XX a b BRACKET ])

MESSAGE("${XX}")

FOREACH(x ${XX})
    STRING(REGEX REPLACE "BRACKET" "[" x ${x})
    MESSAGE("--> ${x}")
ENDFOREACH()



回答2:


As noted in another answer, the square brackets are now used to delimit "long form" arguments or long form comments, as well documented in CMake 3.0 and later.

A single pair of square brackets with ; inside have also long been used to designate registry [key;value] pairs on Windows. An example of this behavior is shown in the CMake file InstallRequiredSystemLibraries.cmake :

get_filename_component(msvc_install_dir
  "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0;InstallDir]" ABSOLUTE)

The way it's implemented has the unfortunate side effect of causing confusion when somebody wants to have list values containing square brackets, hence this question on SO.



来源:https://stackoverflow.com/questions/26057678/escape-characters-in-a-semicolon-separated-list-in-cmake

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!