问题
I want to have a macro that's invoked like this:
GCC_WARNING(-Wuninitialized)
which expands to code like this:
_Pragma("GCC diagnostic ignored \"-Wuninitialized\"")
I'm not having luck getting this to work, as the usual tricks of preprocessor joins and stringifying don't seem to apply or I don't know how to apply them here.
回答1:
With the little help of preprocessor magic:
#define HELPER0(x) #x
#define HELPER1(x) HELPER0(GCC diagnostic ignored x)
#define HELPER2(y) HELPER1(#y)
#define GCC_WARNING(x) _Pragma(HELPER2(x))
GCC_WARNING(-Wuninitialized)
回答2:
Would it also be acceptable if the macro argument is enclosed in single quotes? If so, you could use this:
#define GCC_WARNING(x) _Pragma("GCC diagnostic ignored '" #x "'")
When calling it like GCC_WARNING(-Wuninitialized)
it expands to
_Pragma("GCC diagnostic ignored '" "-Wuninitialized" "'")
I had to make use of the string concatenating behaviour of C (printf("a" "b");
is the same as printf("ab");
) here since using "'#x'"
in a macro would avoid that x
is expanded.
来源:https://stackoverflow.com/questions/8724644/how-do-i-implement-a-macro-that-creates-a-quoted-string-for-pragma