Home > Blockchain >  Passing pre-processor flags that contain special characters [c 17, g ]
Passing pre-processor flags that contain special characters [c 17, g ]

Time:03-14

I am trying to assign a value to a const char* by using a pre-processor flag in the following way.

#include <iostream>

#define ST(A...) #A
#define STR(A) ST(A)

const char* output = STR(FLAG);

int main() {
    std::cout << output;
}

This approach works well, unless FLAG contains some special characters. When I attempt to build the above with

g   .\Main.cpp -std=c  17 -DFLAG="a,b!c)d}e-f"

I get this in the error log. It doesn't like the special characters.

<command-line>: error: expected ',' or ';' before 'd'
.\Main.cpp:4:19: note: in definition of macro 'STR'
    4 | #define STR(A) ST(A)
      |                   ^
.\Main.cpp:6:26: note: in expansion of macro 'FLAG'
    6 | const char* output = STR(FLAG);
      |                          ^~~~
<command-line>: error: expected declaration before '}' token
.\Main.cpp:4:19: note: in definition of macro 'STR'
    4 | #define STR(A) ST(A)
    6 | const char* output = STR(FLAG);
      |                          ^~~~
<command-line>: error: 'e' does not name a type
.\Main.cpp:4:19: note: in definition of macro 'STR'
    4 | #define STR(A) ST(A)
      |                   ^
.\Main.cpp:6:26: note: in expansion of macro 'FLAG'
    6 | const char* output = STR(FLAG);
      |  

The desired output of the program would be a,b!c)d}e-f.

Is there any (sane) way to obtain this functionality using pre-processor flags, or something similar?

CodePudding user response:

You don't have to use stringification macros when FLAG is a string:

-std=c  17 -DFLAG="\"a,b!c)d}e-f\""

Live Demo

  • Related