How to escape accolade characters in CMake

纵然是瞬间 提交于 2019-12-11 21:16:30

问题


I'm manually generating a QtCreator project file (.pro) from CMake.

At some point, I need to write $${VAR} to the .pro file. So I need to escape both the $ character and the { }.

I found out how to protect the $ sign, here is how I proceed:

macro( QMAKE_ADD_LINE_TO_VAR var line )
    set( ${var} "${${var}}\n${line}\n" )
endmacro()

set(PRO_CONTENT "#Generated by CMake scripts!")
# Adding many other stuff here....
QMAKE_ADD_LINE_TO_VAR(PRO_CONTENT "TARGET = \\$\\$VAR" )
file(WRITE file.pro ${PRO_CONTENT} )

This generates file.pro:

#Generated by CMake scripts!
...
TARGET = $$VAR

But how can I generate? I could not find out how to escape the accolades:

#Generated by CMake scripts!
...
TARGET = $${VAR}

I tried:

QMAKE_ADD_LINE_TO_VAR(PRO_CONTENT "TARGET = \\$\\$\\{VAR\\}" )
QMAKE_ADD_LINE_TO_VAR(PRO_CONTENT "TARGET = \\$\\$\{VAR\}" )

with no success...


回答1:


It appears that macro call consume one level of escaping. It is known bug, but CMake developers don't want to fix it (for backward compability reason).

Originally, in CMake there is no needs to escape { character; only ${ combination has a special meaning. So you only need to escape $ sign. Because of macro call, you need to escape it twice:

QMAKE_ADD_LINE_TO_VAR(PRO_CONTENT "TARGET = \\\$\\\${VAR}" )

You may implement QMAKE_ADD_LINE_TO_VAR as a function:

function( QMAKE_ADD_LINE_TO_VAR var line )
    set( ${var} "${${var}}\n${line}\n" PARENT_SCOPE)
endfunction()

In that case, escaping will be simplified:

QMAKE_ADD_LINE_TO_VAR(PRO_CONTENT "TARGET = \$\${VAR}" )


来源:https://stackoverflow.com/questions/32583580/how-to-escape-accolade-characters-in-cmake

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