#define STR1 "s"
#define STR2 "1"
#define STR3 STR1 ## STR2
Is it possible to concatenate have STR3 == "s1"? You can do this by passing args to another Macro function. But is there a direct way?
#define STR1 "s"
#define STR2 "1"
#define STR3 STR1 ## STR2
Is it possible to concatenate have STR3 == "s1"? You can do this by passing args to another Macro function. But is there a direct way?
You don't need that sort of solution for string literals, since they are concatenated at the language level, and it wouldn't work anyway because "s""1" isn't a valid preprocessor token. However, for general token pasting, try this:
Then, e.g.,
PPCAT(s, 1)
produces the identifiers1
.Continuing on the theme are these macros:
Then,
Hint: The
STRINGIZE
macro above is cool, but if you make a mistake and its argument isn't a macro - you had a typo in the name, or forgot to#include
the header file - then the compiler will happily put the purported macro name into the string with no error.If you intend that the argument to
STRINGIZE
is always a macro with a normal C value, thenwill expand it once and check it for validity, discard that, and then expand it again into a string.
It took me a while to figure out why
STRINGIZE(ENOENT)
was ending up as"ENOENT"
instead of"2"
... I hadn't includederrno.h
.If they're both strings you can just do:
The preprocessor automatically concatenates adjacent strings.
EDIT:
As noted below, it's not the preprocessor but the compiler that does the concatenation.