Search code examples
c++cc-preprocessorpragma

Put multiple pragma directives into one preprocessor define


I need to push/pop several gcc diagnostics in my code. If that was needed in a single file I would do the following:

#pragma GCC diagnostic push
#pragma GCC diagnostic error "-Wformat"
#pragma GCC diagnostic error "-Wuninitialized"

...some code...

#pragma GCC diagnostic push

But I need this in multiple locations. So I want to have a #define or something similar. I thought about the following but c preprocessor does not allow #pragmas in #define.

#define PushWarnings \
    #pragma GCC diagnostic push \
    #pragma GCC diagnostic error "-Wformat" \
    #pragma GCC diagnostic error "-Wuninitialized"

Is there a way of achieving this?


Solution

  • Yes, there is a way to do this. C99 introduced the _Pragma operator (also available in C++ since C++11).

    A pragma such as

    #pragma GCC diagnostic error "-Wformat"
    

    can also be written as

    _Pragma("GCC diagnostic error \"-Wformat\"")
    

    The latter is not a # preprocessor directive, so it can be generated from macros:

    #define PushWarnings \
        _Pragma("GCC diagnostic push") \
        _Pragma("GCC diagnostic error \"-Wformat\"") \
        _Pragma("GCC diagnostic error \"-Wuninitialized\"")