Sean Seefried
Sean Seefried

Reputation: 1279

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.

Upvotes: 8

Views: 2754

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477562

You need double indirection magic:

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

#define CONSTANT 42

const char * str = STR(CONSTANT);

Upvotes: 10

Sean Seefried
Sean Seefried

Reputation: 1279

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.

Upvotes: 17

Related Questions