What does the ms-extensions flag do exactly with g

2020-04-11 18:12发布

问题:

GCC has a flag -fms-extensions.

What does this flag do exactly? Why is it sometimes on by default, and why does it exist?

回答1:

According to the gcc 9.1.0 source code (grepped for flag_ms_extensions) the effects are:

  • (C) Allow anonymous unions and structs. These were added to the C11 standard, but the flag will enable them even in older modes such as C99 or Ansi.
  • (C++) Allow a class member to have the same name as its type (e.g. using foo = int; struct A { foo foo; }). With ms-extensions disabled, the behaviour is to accept this code in C (where it is legal); or an extern "C" block unless -pedantic flag was given. The error message for this is declaration of NAME changes meaning of NAME.
  • (C++) Allow implicit int; any situation that would have produced the diagnostic ISO C++ forbids declaration of NAME with no type is now allowed, with int assumed as the type. Examples: const *p; or const f();.
  • (C++) Allow implicit conversion from a qualified-id naming a non-static member function, to a pointer-to-member. In ISO C++ the & operator is required to perform that conversion.
  • (C++) Allow &f to form a pointer-to-member, if f (an unqualified-id) names a non-overloaded member function in that context. ISO C++ requires explicit qualification with the class name.

The flag is turned on by default if the Target ABI is a Microsoft ABI. It can be disabled by manually specifying -fno-ms-extensions.


The rationale behind this is a tougher question. The documentation has to say:

Accept some non-standard constructs used in Microsoft header files.

Disable Wpedantic warnings about constructs used in MFC.

So I assume the rationale is to allow g++ to build MFC applications which depend on non-standard code in MSVC vendor-supplied headers.

I am not sure how relevant that still is in 2019 and I think a good case could be made for gcc to default to having this flag turned off. (Users can always specify it if they want to build an old MFC app).

For example MSVC 19.xx (the latest version to date) no longer allows the last three bullet points in its default mode. (It does still allow foo foo; even with /Za flag).