Guy Rutenberg

Keeping track of what I do

Expanding Macros into String Constants in C

with 5 comments

Today I came across an annoying problem, how do I expand a C macro into a string?

One of C’s preprocessor operators is the # which surrounds the token that follows it in the replacement text with double quotes (“). So, at first the solution sounds pretty simple, just define

#define STR(tok) #tok

and things will work. However, there is one caveat: it will not work if passed another macro. For example,

#define BUF_LEN 100
#define STR(tok) #tok
 
STR(BUF_LEN)

will produce after going through the preprocessor

"BUF_LEN"

instead of "100", which is undesired. This behavior is due to the C standard noting that no macro expansions should happen to token preceded by #.

However, after reconsidering the source of the problem, I’ve found the following workaround: define another macro which will expand the argument and only then call the macro which does the quoting.

#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)
 
#define BUF_LEN 100
 
STR(BUF_LEN)

will produce

"100"

as desired.

Explanation: The STR macro calls the STR_EXPAND macro with its argument. Unlike in the first example, this time the parameter is checked for macro expansions and evaluated by the preprocessor before being passed to STR_EXPAND which quotes it, thus giving the desired behavior.

Share and Enjoy:
  • del.icio.us
  • StumbleUpon
  • Digg
  • Facebook
  • Mixx
  • Google Bookmarks
  • Simpy

Written by Guy

December 20th, 2008 at 8:36 pm

Posted in C/C++,Tips

5 Responses to 'Expanding Macros into String Constants in C'

Subscribe to comments with RSS or TrackBack to 'Expanding Macros into String Constants in C'.

  1. excellent !

    Hai Le

    5 Mar 10 at 02:19

  2. A VERY big thankyou for this workaround.

    Matt

    19 Aug 10 at 03:26

  3. Very good and simple trick! Thanks.

    Peter

    14 Apr 11 at 19:21

  4. thanks very much! very helpful.

    Kasidit

    10 May 11 at 11:57

  5. greate! Thanks a lot.
    I solved my problem with your help.

    YinChao

    23 Dec 11 at 05:15

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">