Question

I've got two structures in two different header files, let's say:

header1.h:

#ifndef HEADER1_H
#define HEADER1_H

#include "header2.h"

typedef struct
{
  Struct2 s;
} Struct1;
#endif

header2.h:

#ifndef HEADER2_H
#define HEADER2_H

#include "header1.h"

typedef struct
{
  Struct1* s;
} Struct2;

#endif


As you can see i declare Struct2 in Struct1 and pointer to Struct1 in Struct2. Obviously when i try to compile this it gives me an error: unknown type name ‘Struct1’ or 'Struct2'. Is there any way to do this or i must change my conception?

Was it helpful?

Solution

If you really want to do this, you can, you just need to use partial declarations before really declaring each structure:

header1.h

#ifndef _HEADER1_H
#define _HEADER1_H

#include "header2.h"

struct struct1
{
      struct struct2 s2;
};
#endif

header2.h

#ifndef _HEADER2_H
#define _HEADER2_H

struct struct1;

struct struct2
{
      struct struct1 *s1;
};

#endif
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top