6

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
ThreeBit
  • 608
  • 6
  • 17

2 Answers2

15

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)
Lindydancer
  • 25,428
  • 4
  • 49
  • 68
  • Thanks but that doesn't work, probably due to the fact that it doesn't put \" around -Wuninitialized. The macro usage above yields the following GCC error: ignoring #pragma GCC diagnostics [-Wunknown-pragmas] – ThreeBit Jan 06 '12 at 03:51
  • It does place quotes around -Wuninitialized. The problem was a typo `diagnostics` instead of `diagnostic` -- I've fixed it in the answer above. – Lindydancer Jan 06 '12 at 17:01
0

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.

Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
  • Almost... actually "_Pragma" has a special meaning for gcc. I was posting a similar solution, but I realized that it doesn't work with my gcc because the preprocessor complains ("error: _Pragma takes a parenthesized string literal"). – Giuseppe Guerrini Jan 04 '12 at 09:59
  • 1
    That won't work -- `_Pragma` interprets its argument before strings are concatenated, so it will see two strings, not one. Unlike `printf`, it is a special construct which follows special rules. – Lindydancer Jan 04 '12 at 09:59
  • Ah, how silly, it didn't occur to me that this was a GCC-specific question. I thought `_Pragma` was some custom debug function but now that I look at the name of the macro, I should've known better. – Frerich Raabe Jan 04 '12 at 10:05
  • 2
    In fact `_Pragma` is not GCC-specific. It's part of the C99 standard to allow macros to expand to a pragma. However, the user asked about a GCC-specific use case, but the question would still be valid for generic pragmas as well. – Lindydancer Jan 04 '12 at 11:29
  • @Lindydancer: Interesting! I didn't even realize that it's part of the C99 standard. Learned something new today. :-) – Frerich Raabe Jan 04 '12 at 19:00