GCC does not honor ‘pragma GCC diagnostic’ to silence warnings [duplicate]

This appears to be a bug in gcc at least. The following code:

#pragma GCC diagnostic ignored "-Wunknown-pragmas"
#pragma GCC diagnostic ignored "-Wuninitialized"

int fn(void) {
    #pragma xyzzy
    int x;
    return x;
}

int main (void) {
    return fn();
}

has no problems ignoring the uninitialised x value but still complains about the pragma (without the uninitialized pragma, it generates a warning for x as you’d expect).

If you change the command line options to be -Wall -Wno-unknown-pragmas, then it ignores it just fine. That’s okay for your specific case since you want it applied over your entire translation unit but it won’t allow the fine-grained control that you would get from the #pragma method (if it worked).


I went to raise a bug report on GCC but found that it already exists (#53431).

While that specific bug has to do with -Wundef, a snippet in one of the comments indicates that it probably applies to all variants affecting the preprocessor (slightly modified for emphasis):

The C++ parser lexes (and preprocesses) before handling the pragmas, whereas the C parser processes the pragmas as it sees them.

We must somehow parse these pragmas also in cp/parser.c:631. Maybe one can do something similar to what we do for cp_parser_initial_pragma, but within the loop and only handling pragma diagnostic. Surely, it will need some trial and error to get it right. If any of you wants to give it a try and need some help, just ask here or in the mailing list.

That explains why we don’t see the same problem with -Wuninitialized, because it’s detected during later stages of the compilation process, after the pragmas have been activated at the end of preprocessing.

So, if you want to see it fixed in a more timely manner (it was raised over three years ago), I’d suggest (as I have) hassling the GCC bugzilla site to try get some exposure.


Update: Based on the linked bug report, it looks like this issue will be fixed in gcc-13 but, as of yet, no ETA on that release. As of Feb 22, 2023, status is as follows:

The GCC development branch which will become GCC 13 is in regression and documentation fixing mode (Stage 4) until we reach zero P1 regressions and branch for the release.

We are making slow progress towards this goal, new bugs are coming in at a high pace.

Please help triaging UNCONFIRMED reported regressions and at least provide some analysis for bugs attributed to you or in the area of your expertise when they are classified as target bugs.

Quality Data:

Priority Count Change
P1 32 -5
P2 492 -5
P3 77 -11
P4 255 -1
P5 24
Total P1-P3 601 -21
Total 880 -22

So, if you want to see this fixed in a more timely manner, please get involved in the process, even if that’s only providing more information on the serious (P1) issues.

Leave a Comment