Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake function to convert string to C string literal

Tags:

cmake

Is there a built-in function to convert a string to a C string literal. For example:

set(foo [[Hello\ World"!\]])
convert_to_cstring_literal(bar "${foo}")
message("${foo}") # Should print (including quotes): "Hello\\ World\"!\\"

I mean I can do this with considerable effort with regexes, but if there's a built-in function it would be a lot nicer.

like image 849
Timmmm Avatar asked Oct 24 '25 17:10

Timmmm


1 Answers

Turning my comment into an answer

Slightly modifying the CMake's function _cpack_escape_for_cmake from CPack.cmake I was able to successfully test the following:

cmake_minimum_required(VERSION 2.8)

project(CStringLiteral)

function(convert_to_cstring_literal var value)
    string(REGEX REPLACE "([\\\$\"])" "\\\\\\1" escaped "${value}")
    set("${var}" "\"${escaped}\"" PARENT_SCOPE)
endfunction()

set(foo [[Hello\ World"!\]])

convert_to_cstring_literal(bar "${foo}")
message("${bar}") # prints "Hello\\ World\"!\\"
like image 101
Florian Avatar answered Oct 26 '25 15:10

Florian