c++cmake

CMakeLists - add_definition add double quotes around variable


I'm trying to pass a definition in the compiler flags in my C++ project configured with CMake as shown below, as suggested in the post here:

execute_process(COMMAND git describe --abbrev=4 --dirty --always --tags 
OUTPUT_VARIABLE GIT_VERSION)

add_definitions(-DVERSION="\\"${GIT_VERSION}\\"")

I'm seeing a lexing error. How do I add quotes around the variable for compiler definitions?

My desired output is

-DVERSION="v1.0"

Solution

  • What you are looking for is the CMake escape character \ to be paired with another character. From the CMake escape sequences documentation:

    A \ followed by one of ()#" \#@^ simply encodes the literal character without interpreting it as syntax.

    You didn't specify what your expected result should be, but here are a couple options. So, if you're just looking to put double-quotes around the GIT_VERSION variable, try this (as @GAVD suggested):

    # Yields -DVERSION="2.23.0"
    add_definitions(-DVERSION=\"${GIT_VERSION}\")
    

    You shouldn't even need escape characters for one set of quotes in add_definitions():

    # Yields -DVERSION="2.23.0"
    add_definitions(-DVERSION="${GIT_VERSION}")
    

    If you're looking to add two sets of double-quotes around the variable, try this:

    # Yields -DVERSION=""2.23.0""
    add_definitions(-DVERSION="\"${GIT_VERSION}"\")
    

    If you're trying to get the format shown in your linked post, try this:

    # Yields -DVERSION="\"2.23.0"\"
    add_definitions(-DVERSION="\\\"${GIT_VERSION}"\\\")