The question seems to be a classic one, but I didn’t find an answer:
I have two struct type written in C —— struct type A and struct type B, and B use A while A use B at the same time.
In a.h:
#include "b.h"
struct B;
typedef struct A {
void (*func)(struct B* b);
}A;
In b.h:
#include "a.h"
typedef struct B {
A a;
}B;
though this will work, it has a consequence — when using the function fun “func”, if I pass a variable declared in the form:
B* someb;
not:
struct B* someb;
there will be a warning when compiling, saying incompatible pointer type. Is this normal? could I avoid this warning?
From your
a.hheader file, simply remove the line#include "b.h". The forward declarationstruct B;is all you need.That change will fix the circular include dependency, and will make any code using these headers more sane.
Then, wherever you want to make use of the
Bstruct, simply includeb.h, and use it with or without thestructkeyword.Some code to illustrate : the
a.hheader file :The
b.hheader file :A file that uses these header files :
Both
funandfun2are just fine (from the compiler point of view –funchasn’t been initialized, so calling it will cause an issue at run time).