Albus Dumbledore Albus Dumbledore - 17 days ago 8
C Question

Creating a string literal from a define

Lets say I have a define like so:

#define MY_FUNC_NAME my_func


I want to get a string literal for it, e.g.
"my_func"
.

I tried using the hash preprocessor operator like so:

#define str(s) #s
#define MY_FUNC_NAME_LITERAL str(MY_FUNC_NAME)


But this would yield
"MY_FUNC_NAME"
instead of
"my_func"
, as though it does not replace it before creating the literal.

Any ideas how to achieve that?

Answer

Like the GCC documentation explains, you need two macros to do that

 #define xstr(s) str(s)
 #define str(s) #s
 #define foo 4
 str (foo)
      ==> "foo"
 xstr (foo)
      ==> xstr (4)
      ==> str (4)
      ==> "4"