How to turn a macro into a string using cpp?

GNU cpp allows you to turn macro parameters into strings like this

#define STR(x) #x 

Then STR(hi) is replaced by "hi"

But how do you turn a macro (not a macro parameter) into a string?

Say I have a CONSTANT macro with some value, for example.

 #define CONSTANT 42 

This does not work: STR(CONSTANT) . This gives "CONSTANT" what we do not want.

+6
source share
2 answers

The trick is to define a new macro that calls STR .

 #define STR(str) #str #define STRING(str) STR(str) 

Then STRING(CONSTANT) gives "42" as desired.

+14
source

You need a double magic of treatment:

 #define QUOTE(x) #x #define STR(x) QUOTE(x) #define CONSTANT 42 const char * str = STR(CONSTANT); 
+10
source

Source: https://habr.com/ru/post/893734/


All Articles