How do I implement a macro that creates a quoted string for _Pragma?

女生的网名这么多〃 提交于 2020-01-13 09:36:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!