Consider this:
#define STRINGIFY(A) #A
If I then later write:
STRINGIFY(hello)
Is the compiler actually seeing this:
#hello
I think it is that additional hash in front of #A
that is confusing me.
Consider this:
#define STRINGIFY(A) #A
If I then later write:
STRINGIFY(hello)
Is the compiler actually seeing this:
#hello
I think it is that additional hash in front of #A
that is confusing me.
No, the compiler will put the argument between quotes, resulting in this:
However, beware that macro substitution doesn't take place near
#
and##
, so if you really need to stringify the argument (even if it's another macro) it's better to write two macros, the first one to expand the argument and the other one to add quotes:Or more generally, if you're compiler supports variadic macros (introduced in C99):
If you really need a function-like macro that paste a
#
at the beginning of the argument, I think you need it to generate a string (otherwise you'd make an invalid token for the compiler), so you could simple generate two string literals that the compiler will "paste":The
main
body will look like this in the preprocessor output:I hope this is not an obscure corner of the preprocessor that results in undefined behavior, but it shouldn't be a problem since we're not generating another preprocessor instruction.
You can test it yourself using the
-E
(*) flag (with gcc/g++):test.cpp
Output of
g++ test.cpp -E
(*):
If you use the -E option, nothing is done except preprocessing.
- GCC Options Controlling the PreprocessorFound good, simple explanation of using hash in preprocessor here:
http://www.cplusplus.com/doc/tutorial/preprocessor/
What the compiler sees is this:
The hash is preprocessor-only token.
Single hash stringifies the argument.
gets replaced by
Double hash concatenates the tokens:
gets replaced by this:
and then by this:
EDIT: As Pubby pointed out, the example was wrong, the macro replacement doesn't work that way, but now I corrected it.