Search code examples
macrosc-preprocessorstringification

Preprocessor Quoting macro arguments


Suppose I have some macro #define NAME name, and I want to define some other macro which will expand to the quoted value. That is, as if I had also defined #define NAME_STR "name". Is there a neater way than the following?

#define QUOT(str)   #str
#define QUOT_ARG(str)   QUOT(str)
#define NAME_STR    QUOT_ARG(NAME)

Solution

  • Not really, due to the fact that macro arguments are not expanded when used in stringification. From the GNU C PreProcessor manual:

    Unlike normal parameter replacement, the argument is not macro-expanded first. This is called stringification.

    From the same source:

    If you want to stringify the result of expansion of a macro argument, you have to use two levels of macros.

    ...which continues with an example:

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