Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding Circular Dependency in C header files

 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".

like image 696
Pkp Avatar asked Jun 25 '26 12:06

Pkp


2 Answers

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.

like image 110
kfsone Avatar answered Jun 28 '26 04:06

kfsone


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_ */
like image 33
r3mainer Avatar answered Jun 28 '26 05:06

r3mainer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!