forward declaration of typedefed structs

3.7k Views Asked by At

In C often structs are typedefed to avoid writing struct everywhere.

When using this names as opaque pointer parameters in headers you have to forward declare them. It is rather annoying that the whole typedef has to be duplicated.

Example:

some header defines some types:

typedef struct sBlaBlaFooBar{
 int someData;
}BlaBlaFooBar;

Some other header uses this structure as pointer parameter. But to avoid huge include dependencies BlaBlaFooBar.h should not be included and just a forward declaration is used.

So you have to write typedef struct sBlaBlaFooBar BlaBlaFooBar; to forward declare it.

That does bother me is the redundancy that i have to know the tag name of the structure because normally it does not matter. And if it is changed, all the forward declarations also have to be changed even if the typename is the same.

Is there some smart way around this?


more detailed explanation:

  • a lot of headers with structure definitions (that may be also composed structures (just to show deep dependency graphs))
    • s1.h
    • s2.h
    • s3.h
    • s4.h
  • a BlaBlaFooBar header with a BlaBlaFooBar structure that is a composite of all these.
  • Additional structures BlaBlaBarFoo with similar topology (from other sub structures)
  • then modules that defines new structures NewStruct and functions NewStruct_create(NewStruct* out, const BlaBlaFooBar* in); that processes the above structures as input. These headers only need the typedefs and only the implementation has to know about exact BlaBlaFooBar structure definitions.
  • Addional modules that only work on NewStruct and to not necessarily have to be recompiled if BlaBlaFooBar changes.

So to avoid these kind of dependencies the structures have to be forward declared in the header and the c-file includes the definition.

1

There are 1 best solutions below

2
On BEST ANSWER

Use 2 include files:

blabla.h

#include "light_dependencies.h"
typedef struct sBlaBlaFooBar BlaBlaFooBar;

blabla_internal.h

#include "blabla.h"
#include "heavy_dependencies.h"
struct sBlaBlaFooBar {
    ...
};

blabla.c

#include "blabla_internal.h"
/* Here is code which deals with the internals of the struct */

usercode.c

#include "blabla.h"
/* Here is code which only passes struct pointers around */