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 functionsNewStruct_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 exactBlaBlaFooBar
structure definitions. - Addional modules that only work on
NewStruct
and to not necessarily have to be recompiled ifBlaBlaFooBar
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.
Use 2 include files:
blabla.h
blabla_internal.h
blabla.c
usercode.c