Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn a macro into a string using cpp?

GNU's cpp allows you to turn macro parameters into strings like so

#define STR(x) #x

Then, STR(hi) is substituted with "hi"

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

Say I have a macro CONSTANT with some value e.g.

#define CONSTANT 42

This doesn't work: STR(CONSTANT). This yields "CONSTANT" which is not what we want.

like image 836
Sean Seefried Avatar asked Jul 28 '11 00:07

Sean Seefried


2 Answers

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

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

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

like image 64
Sean Seefried Avatar answered Oct 13 '22 10:10

Sean Seefried


You need double indirection magic:

#define QUOTE(x) #x
#define STR(x) QUOTE(x)

#define CONSTANT 42

const char * str = STR(CONSTANT);
like image 37
Kerrek SB Avatar answered Oct 13 '22 11:10

Kerrek SB