I have a structure with no members (for the moment) and I would like to know if it is possible to suppress the warning I get:
warning: struct has no members
Is it possible to add a member and keep the sizeof
the struct zero? Any other solution?
If you're not requiring "too strict" adherence, you might get away with this:
This is a GCC extension, though.
I was kind of hoping I'd be able to use the C99 feature called "flexible arrays", declared like this:
but that doesn't work; they require that there is at least one normal struct member first, they can't be the only member.
In c the behaviour of an empty structure is compiler dependent versus c++ where it is part of the spec (explanations here)
in C it is rather more murky since the c99 standard has some language which implies that truly empty structures aren't allowed (see TrayMan's answer) but many compilers do allow it (e.g gcc).
Since this is compiler dependent it is unlikely that you will get truly portable code in this case. As such non portable ways to suppress the warning may be your best bet.
if you just need the struct symbol for casting and function arguments then just:
this will create the symbol for an opaque type.
Technically this isn't even valid C.
TrayMan was a little off in his analysis, yes 6.2.6.1 says:
but tie that with 6.2.5-20, which says:
and now you can conclude that structures are going to be one or more bytes because they can't be empty. Your code is giving you a warning, while the same code will actually fail to compile on Microsoft's Visual Studio with an error:
So the short answer is no, there isn't a portable way to avoid this warning, because it's telling you you're violating the C standards. You'll have to use a compiler specific extension to suppress it.
Nope. FWIW, C++ allows empty structs but the sizeof() is always non-zero for an empty struct.
Not any easy ones. It's worth noting that empty structs are only somewhat supported in C and disallowed in C99.
Empty structs are supported in C++ but different compilers implement them with varying results (for sizeof and struct offsets), especially once you start throwing inheritance into the mix.
C99 standard is somewhat ambiguous on this, but seems to say that an empty struct should have non-zero size.