Guy Rutenberg

Keeping track of what I do

Expanding Macros into String Constants in C

with one comment

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

One Response 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

Leave a Reply