Click to See Complete Forum and Search --> : C struct : problem with structs containing each other


mevuorin
07-05-2005, 04:14 PM
Hi

I'm having problems getting my structs to compile. I tried to find a solution from my K&R C book and the web, but couldn't. It's really annoying, because it's probably just some syntax problem, but I just can't figure it out.

Basically I'm trying to have two structs that both contain member whose type is the other struct.

Here's the problem ( simplified from my code ):

a.h:

#ifndef _A_H_
#define _A_H_

#include"b.h"

typedef struct{
b_struct bs;
} a_struct;

#endif

b.h:

#ifndef _B_H_
#define _B_H_

#include"a.h"

typedef struct{
a_struct as;
} b_struct;

#endif

c.c:
#include"a.h"

When I try to compile, I get:

C:\Program Files\eclipse\workspace\testi>gcc c.c
In file included from a.h:4,
from c.c:1:
b.h:7: error: parse error before "a_struct"
b.h:7: warning: no semicolon at end of struct or union
b.h:8: warning: data definition has no type or storage class
In file included from c.c:1:
a.h:7: error: parse error before "b_struct"
a.h:7: warning: no semicolon at end of struct or union
a.h:8: warning: data definition has no type or storage class

What's wrong and how to fix it?

Thanks for reading and for any advice/pointers in advance.

mevuorin
07-07-2005, 05:04 AM
I got some advice, and found out, that the problem was basically that I didn't use pointers. Because I didn't use pointers, compiler couldn't figure out the size of structs a and b and complained. With pointers it works, because the size of all pointers is the same and known to compiler.

Here's the solution I ended up with:
//A.h
#ifndef _A_H_
#define _A_H_

#include"b.h"

typedef struct _a_struct{
struct _b_struct *bs;
} a_struct;

#endif /*_A_H_*/

//B.h
#ifndef _B_H_
#define _B_H_

#include"a.h"

typedef struct _b_struct{
struct _a_struct *as;
} b_struct;

#endif /*_B_H_*/

//C.c
#include"a.h"

Compiles and works. Finally.

slavik
07-07-2005, 01:29 PM
why typedef them? in the working example, you don't need the typedefs ...

mevuorin
07-08-2005, 05:21 AM
Typedefs were used int the example, because I used them in my original code from which the example was simplified and they were part of the problem. In my original code, I used typedefs to make a struct that was used a lot easier to use and to make code easier to read.