Bort
Bort

Reputation: 7618

Avoiding "redefinition of typedef" warnings when defining structs

I'm defining some structs which reference eachother, and typedef'ing the structs before using them, so each struct is 'aware' of the others (was getting compilation errors without this). Not sure if this is necessary, or correct.

Now when compiling with gcc, I'm getting "redefinition of typedef" warnings. What's the correct way to go about this?

typedef struct a A;
typedef struct b B;
typedef struct c C;

struct a {
    B* list;
    A* parent;
};

struct b {
    A* current;
    B* next;
};

struct c {
    A* current;
    A* root;
};

UPDATE: Dumb, bad copy-pasting resulted in this header being included twice in another file. I'm new to C and thought it must have something to do with having the structs in the file twice. Thanks @Kevin Ballard for the heads up.

Upvotes: 3

Views: 6843

Answers (2)

perreal
perreal

Reputation: 97938

This is a good example of why header/include guards are needed:

#ifndef MY_HEADER_FILE
#define MY_HEADER_FILE

typedef struct a A;
typedef struct b B;
/* ... */

#endif

Upvotes: 7

Ed Swangren
Ed Swangren

Reputation: 124632

There is no error in your code that I can see now that you have added the semi-colons. You can also just forward declare the types like so:

struct b;
struct c;

typedef struct a {
    struct b* list;
    struct a* parent;
} A;

typedef struct b {
    A* current;
    struct b* next;
} B;

typedef struct c {
    A* current;
    A* root;
} C;

Your way is fine though, avoids typing struct a few times.

Upvotes: 1

Related Questions