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.