Does CMake support raw strings?

Viewed 316

For example, one might want to use the install() command to run CMake code at install time. Code of this form is usually something like:

install(CODE "
message(STATUS "The value of \${VAR} is \"\${VAL}\"
")

In this case, each $ is escaped as we want the expansion to be performed at install time, not when the string is first parsed by CMake. In addition, nested quotes also need to be escaped. For larger commands, this can quickly become onerous -- it can be easy to forget to escape quotes and $s.

Is there a better way?

1 Answers

CMake, since version 3.0, does indeed support raw strings -- they are called bracket arguments. For example:

install(CODE [=[
message(STATUS "The value of ${VAR} is ${VAL}")
]=])

The number of = separating the delimiters [=[ in ]=] is optional; more =s can be used if you need to embed a literal ]=] in the code string.

Note that CMake variable expansions are not performed within bracket arguments. To illustrate:

set(VAR "Variable")
set(VAL "Value")

set(CODE [=[
message(STATUS "The value of ${VAR} is ${VAL}")
]=])

message(STATUS "${CODE}")
cmake_language(EVAL CODE "${CODE}")

Executing this in a script via cmake -P code.cmake will print:

$ cmake -P test.cmake
-- message(STATUS "The value of ${VAR} is ${VAL}")

-- The value of Variable is Value

message(STATUS "${CODE}") echos the embedded CMake code verbatim; cmake_language(EVAL CODE "${CODE}") evaluates the CMake code and produces its resulting output.

Related