Search code examples
c++gccc-preprocessortokensuppress-warnings

parameterized warning silencing macro trouble


The following doesn't compile:

#define SUPPRESS(w) _Pragma("GCC diagnostic ignored " ## w)

SUPPRESS("-Wuseless-cast")

int main() {
    int a = (int)4;
    return a;
}

Here's the error:

error: pasting ""GCC diagnostic ignored "" and ""-Wuseless-cast"" does not give a valid preprocessing token

How can I get it to work?


Solution

  • The thing is that _Pragma wants to have an escaped string-literal like so

    _Pragma("GCC diagnostic ignored \"-Wuseless-cast\"")
    

    So the trick is to add another layer of stringyfication between the call of SUPPRESS and the call of _Pragma like below

    #define xSUPPRESS(w) _Pragma(#w)
    #define SUPPRESS(w) xSUPPRESS(GCC diagnostic ignored w)
    
    SUPPRESS("-Wuseless-cast")
    

    See it here in action.