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

时光总嘲笑我的痴心妄想 提交于 2019-12-05 07:57:52

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)

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.

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