How do I turn a macro into a string using cpp?
Asked Answered
T

2

8

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.

Tedmund answered 28/7, 2011 at 0:37 Comment(1)
I assume you want the output to be "42" -- I don't think you can without writing a function.Ietta
T
17

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.

Tedmund answered 28/7, 2011 at 0:39 Comment(2)
I believe an ampersand used like this is commonly referred to as the macro "stringize" operator.Zia
That's a hash (#).Cotinga
R
10

You need double indirection magic:

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

#define CONSTANT 42

const char * str = STR(CONSTANT);
Reinhart answered 28/7, 2011 at 0:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.