3

I've got two header files, each requiring a type defined in the other. When I try to compile, I get an error regarding an unknown type name. (If I provide only struct declarations and not definitions, I get an incomplete-types error.) What's a solution that will let me share these structs properly?

Right now, my code looks rather like the following (just imagine the #ifndef preprocessor directives etc.):

<headerA.h>

#include "headerB.h"
typedef struct { 
  mytypeB myB;
} mytypeA;

<headerB.h>

#include "headerA.h"
typedef struct {} mytypeB;
void foo( mytypeA * myA);
JellicleCat
  • 26,352
  • 22
  • 102
  • 152

3 Answers3

5

You should forward-declare the struct mytypeA instead of including headerA.h:

Inside headerB.h:

struct mytypeA; // <<<--- Forward declaration

void foo(struct mytypeA* myA);

This works because you are not using the actual mytypeA, only a pointer to it. You cannot pull the same trick with headerA, because mytypeA includes the actual mytypeB.

Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
1

You can forward declare a structure without needing to define the whole thing.

Carl Norum
  • 210,715
  • 34
  • 410
  • 462
0

These SO questions might help you since it is related to your question.

undefined C struct forward declaration

How to declare a structure in a header that is to be used by multiple files in c?

Community
  • 1
  • 1
minus
  • 706
  • 5
  • 14