Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

repeat typedef struct

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)

// 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 follow


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 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?

Name: Anonymous 2010-01-12 19:20

>>8
Well that's nice, since this is C. C++ doesn't have this problem, because a) it allows referring to struct tags without the keyword, and b) it allows duplicate typedefs, either of which solve the problem. Nice fail.

>>7
Yeah, I think I'll probably do this. Pretty shitty but, ah well, better than writing struct everywhere.

the C standard will probably never change so much because it would break millions of lines of existing code.
Allowing duplicate typedefs wouldn't actually break anything; it's just a relaxation of the current rules. But you're right though, no one seems to care about this issue so it will never change.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List