This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

How to use pragma in a compound literal in GCC 9


A project I help maintain has had a report that it fails to compile with GCC 9
https://github.com/wahern/cqueues/issues/212#issuecomment-461693111

I've attached a minimal reproduction of the issue.
Trying to compile it results in:

<source>: In function 'main':
<source>:46:15: error: lvalue required as unary '&' operand
   46 |     void *x = &quietinit((struct bar){ 0, .a = 0 });
      |               ^
Compiler returned: 1
/*
 * C O M P I L E R  A N N O T A T I O N S
 *
 * GCC with -Wextra, and clang by default, complain about overrides in
 * initializer lists. Overriding previous member initializers is well
 * defined behavior in C. We rely on this behavior to define default,
 * overrideable member values when instantiating configuration objects.
 *
 * quietinit() guards a compound literal expression with pragmas to
 * silence these shrill warnings. This alleviates the burden of requiring
 * third-party projects to adjust their compiler flags.
 *
 * NOTE: If you take the address of the compound literal, take the address
 * of the transformed expression, otherwise the compound literal lifetime is
 * tied to the scope of the GCC statement expression.
 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#if defined __clang__
#define PRAGMA_PUSH _Pragma("clang diagnostic push")
#define PRAGMA_QUIET _Pragma("clang diagnostic ignored \"-Winitializer-overrides\"")
#define PRAGMA_POP _Pragma("clang diagnostic pop")

#define quietinit(...) \
	PRAGMA_PUSH PRAGMA_QUIET __VA_ARGS__ PRAGMA_POP
#elif (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) || __GNUC__ > 4
#define PRAGMA_PUSH _Pragma("GCC diagnostic push")
#define PRAGMA_QUIET _Pragma("GCC diagnostic ignored \"-Woverride-init\"")
#define PRAGMA_POP _Pragma("GCC diagnostic pop")

/* GCC parses the _Pragma operator less elegantly than clang. */
#define quietinit(...) \
	__extension__ ({ PRAGMA_PUSH PRAGMA_QUIET __VA_ARGS__; PRAGMA_POP })
#else
#define PRAGMA_PUSH
#define PRAGMA_QUIET
#define PRAGMA_POP
#define quietinit(...) __VA_ARGS__
#endif

struct bar {
	int a;
};

int main() {
    void *x = &quietinit((struct bar){ 0, .a = 0 });
}

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]