Name: Anonymous 2010-01-12 1:18
Why can't I repeat a typedef struct in C? Why is it allowed in C++ but not C?
I'm running into problems with my header files. Let's say I've got structs Foo, Bar, and Baz. I'd like Foo functions to take Bar and Baz pointer arguments. I shouldn't need to include their header files in Foo.h however; it should just take a forward declaration to reduce interdependency and compilation time. However the multiple declarations break in Foo.c.
Example: (include guards not shown)
So, how do I solve this problem? Just including the other headers in Foo.h works here, but it has the dependency issues, and only works because the relationship is one way; if Baz has some methods take take Foos, this doesn't work. I'm quite wary of unnecessary includes; my last few sepples projects take AGES to compile despite being small because of interdependencies, and I'd really like to avoid this with this next C project.
Best solution I can come up with is just to forward declare
I'm running into problems with my header files. Let's say I've got structs Foo, Bar, and Baz. I'd like Foo functions to take Bar and Baz pointer arguments. I shouldn't need to include their header files in Foo.h however; it should just take a forward declaration to reduce interdependency and compilation time. However the multiple declarations break in Foo.c.
Example: (include guards not shown)
// Bar.h
typedef struct Bar {
int x;
};// Baz.h
typedef struct Baz {
float y;
};// Foo.h
typedef struct Bar Bar;
typedef struct Baz Baz;
typedef struct Foo {
Bar* bar;
Baz* baz;
};
void FooABar(Foo* self, Bar* bar);
void FooABaz(Foo* self, Baz* baz);// Foo.c
#include "Bar.h"
#include "Baz.h"
#include "Boo.h" // ERROR, duplicate typedefs
// implementations followSo, how do I solve this problem? Just including the other headers in Foo.h works here, but it has the dependency issues, and only works because the relationship is one way; if Baz has some methods take take Foos, this doesn't work. I'm quite wary of unnecessary includes; my last few sepples projects take AGES to compile despite being small because of interdependencies, and I'd really like to avoid this with this next C project.
Best solution I can come up with is just to forward declare
struct Bar, and use that as the pointers everywhere instead of just Bar. Is this really what I need to do? If this is the case, I'm thinking I'll just axe the typedefs altogether throughout my entire project. I hate having to write struct everywhere, but I would do it for consistency... How does everyone else solve this?