Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Header files recursion in C

I have this situation:

A.h and B.h

In A.h:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

typedef struct TypeA TypeA_t;
struct TypeA {
...
TypeA_t *a;
void (*doSomething)(TypeB_t*);
};

In B.h:

typedef struct TypeB TypeB_t;
struct TypeB {
...
TypeB_t *b;
TypeA_t something;
};

What’s the correct way to include header files in each file?

If I include A.h in B.h and B.h in A.h I get:

error: unknown type name 'TypeB_t' in A.h

and

error: unknown type name 'TypeA_t' in B.h

I found a similar question here but it doesn’t work in my case.

>Solution :

The way you’ve defined your code, TypeA can live with a forward reference to TypeB, but TypeB needs the full declaration of TypeA to compile.

In other words, you need to do two things. First forward define TypeB in a.h before your class definition (because pointers can work with partial definitions):

//a.h
typedef struct TypeB TypeB_t;

typedef struct TypeA TypeA_t;
struct TypeA {
...
TypeA_t *a;
void (*doSomething)(TypeB_t*);
};

And then include a.h from b.h to get the declaration for your class (because you use the full TypeA class as a field type):

// b.h
#include "a.h"

typedef struct TypeB TypeB_t;
struct TypeB {
...
TypeB_t *b;
TypeA_t something;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading