Why do gcc support empty struct extension for?

Brian Dessent brian@dessent.net
Thu Oct 16 06:45:00 GMT 2008


tiande wrote:

> In C++ context, I understand that it might be used as base class.
> But I don't understand, what does it for in C context? What is the
> reason we used empty struct in C.

It sounds like you're asking about incomplete types.  As long as you
don't try to dereference any fields of a struct, the compiler doesn't
need to see its complete definition in order to allow pointers to that
struct to be used.  This is useful in libraries where you want to hide
implementation details from the user of the library.

For example in the public header of a library you might find:

typedef struct internal_FOO FOO_t;
FOO_t *FOO_create (void);
void FOO_consume (FOO_t *);

This declares a FOO_t type and two functions that return and receive
pointers to this type.  The user of the library (and the compiler) has
no idea what the actual members of "struct internal_FOO" might be, but
that doesn't matter as it's meant to be opaque.  The user of the library
can use the interface as if it were any regular type:

FOO_t *bar = FOO_create();
FOO_consume (bar);

Then in the internal library implementation there will be a definition
of the complete type:

struct internal_FOO
  {
    int a;
    double b;
    ...
  }

But because it's internal it can be rearranged or redesigned at will. 
This works because the C standard says that structs of the same tag
always refer to the same type.  So as to the "why", it's because this is
a part of ISO C and there's tons of code that relies on it.

As to why you'd see something like just "struct bar;", it's because it's
required to first declare the struct tag if you want to use it as an
abstract type, e.g.

struct bar;
void function (struct bar *arg);

This is essentially the same thing as above except without using a
typedef -- the actual fields of "struct bar" are unknown and could be
anything, but as long as it is just a pointer and there's no dereference
the compiler doesn't need them.

Brian



More information about the Gcc-help mailing list