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 10:57

My solution to this in a small project was to make a forward declaration header file, which was included by the main header file so that all the .c files could use the structures. The downside obviously is that you must maintain this file; you could write a script to generate the forward declarations from all other header files, but then you increase compilation complexity.

The real solution is to make a new systems language with module support, but the C standard will probably never change so much because it would break millions of lines of existing code.

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