Search code examples
crecursionheaderinclude

C recursive header file inclusion problem?


Suppose you have to related structures defined in 2 header files like below:

a.h contents:

#include b.h

typedef struct A
{
  B *b;
} A;

b.h contents:

#include a.h

typedef struct B
{
  A *a;
} B;

In such this case, this recursive inclusion is a problem, but 2 structures must point to other structure, how to accomplish this?


Solution

  • Google C/C++ guidelines suggests:

    Don't use an #include when a forward declaration would suffice

    That'd mean:

    a.h contents:

    typedef struct B B;
    
    typedef struct A
    {
      B *b;
    } A;
    

    b.h contents:

    typedef struct A A;
    
    typedef struct B
    {
      A *a;
    } B;
    

    If you prefer something a bit safer (but longer to compile) you can do this:

    a.h contents:

    #pragma once
    typedef struct A A;
    
    #include "B.h"
    
    typedef struct A
    {
      B *b;
    } A;
    

    b.h contents:

    #pragma once
    typedef struct B B;
    
    #include "A.h"
    
    typedef struct B
    {
      A *a;
    } B;