How to implement a macro that creates a quoted string for _Pragma?

I want to have a macro that is called as follows:

GCC_WARNING(-Wuninitialized) 

which expands to this code:

 _Pragma("GCC diagnostic ignored \"-Wuninitialized\"") 

I’m not lucky that this will work, since the usual preprocessor tricks are combined and built, it seems, are not applied or I don’t know how to apply them here.

+6
source share
2 answers

With a little help from 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) 
+14
source

Would it also be acceptable if the macro argument is enclosed in single quotes? If so, you can use this:

 #define GCC_WARNING(x) _Pragma("GCC diagnostic ignored '" #x "'") 

When you call it as GCC_WARNING(-Wuninitialized) , it expands to

 _Pragma("GCC diagnostic ignored '" "-Wuninitialized" "'") 

I had to use the string concatenation behavior of C ( printf("a" "b"); "'#x'" same as printf("ab"); ), since using "'#x'" in the macro would avoid the x extension.

0
source

Source: https://habr.com/ru/post/905067/


All Articles