Empty structure in C

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?


Solution 1:

In c the behaviour of an empty structure is compiler dependent versus c++ where it is part of the spec (explanations here)

C++
A class with an empty sequence of members and base class objects is an empty class. Complete objects and member subobjects of an empty class type shall have nonzero size.

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.

  • In VS you would use #pragma warning
  • in GCC from 4.2.1 you have Diagnostic Pragmas

Solution 2:

if you just need the struct symbol for casting and function arguments then just:

typedef struct _Interface Interface;

this will create the symbol for an opaque type.

Solution 3:

Technically this isn't even valid C.

TrayMan was a little off in his analysis, yes 6.2.6.1 says:

Except for bit-fields, objects are composed of contiguous sequences of one or more bytes, the number, order, and encoding of which are either explicitly specified or implementation-defined.

but tie that with 6.2.5-20, which says:

— A structure type describes a sequentially allocated nonempty set of member objects (and, in certain circumstances, an incomplete array), each of which has an optionally specified name and possibly distinct type.

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:

error C2016: C requires that a struct or union has at least one member

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.