header1.h
-----------------
struct A{
int a;
B *b;
};
header2.h
-------------------
#include"header1.h"
typedef struct b{
int aa;
char bb;
int cc;
}B;
main.c
--------------------
#include<header2.h>
main(){
struct A *ace;
ace = malloc(sizeof(struct A));
ace->b = malloc(sizeof(B));
}
The problem: Basically, header1.h needs to use a struct defined in header2.h.
The Dilemma: Since header2.h includes header1.h, If i include header2.h in header1.h I will be introducing a circular dependency.
Some solutions: One way to solve the problem would be use a void pointer, but is there any other way? I tried forward declaring it, but it says "redifining a typedef".
So the problem you have is the pointer
B *b;
in struct A. Since this is a pointer an incomplete type is ok as long as you tell it that's what this is.
typedef struct a {
int a;
struct B *b;
} A;
or you could use the prototype form:
struct B;
typedef struct a {
int a;
B *b;
};
The compiler just wants to know what type of thing the pointer points-to just here, it doesn't actually care what it looks like in more detail until you first start trying to dereference it.
You can easily prevent your header files from being included multiple times by wrapping them like this
#ifndef FOO_H_ /* include guard */
#define FOO_H_
/* * * * * insert foo.h here * * * * */
#endif /* FOO_H_ */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With