2013Asker
2013Asker

Reputation: 2068

Interdependent headers not compiling

I have 2 headers that depend on each other, both are guarded. But compilation fails as if the type weren't declared:

error: unknown type name Type_1

the first header:

#ifndef HEADER1_H
#define HEADER1_H

#include "header2.h"

typedef struct {
    int a;
    char *b;
} Type_1;

void function(Type_3 *type_3);

#endif

second header

#ifndef HEADER2_H
#define HEADER2_H

#include "header1.h"

typedef struct {
    int a;
    char *b;
    Type_1 *c;
} Type_2;

typedef struct {
    int a;
    char *b;
    Type_2 *c;
} Type_3;


#endif

How to solve it without resorting to hacks?

Upvotes: 1

Views: 871

Answers (3)

Roman Arzumanyan
Roman Arzumanyan

Reputation: 1814

As you use your structures as imcomplete data types, forward declaration is enough:

#ifndef HEADER2_H
#define HEADER2_H

struct Type1;
typedef struct Type1 Type1;

typedef struct {
    int a;
    char *b;
    Type_1 *c;
} Type_2;

typedef struct {
    int a;
    char *b;
    Type_2 *c;
} Type_3;


#endif

Apply same technique to second file. Though, in source code, you need to include header if you don't use your structures as incomplete types. More information about incomplete data types is available in this MSDN article

Upvotes: 0

ldav1s
ldav1s

Reputation: 16315

You must forward declare at least one struct. I'd personally put them all in one header, since there's not that much there.

First header:

#ifndef HEADER1_H
#define HEADER1_H

#include "header2.h"

typedef struct Type_1 {
    int a;
    char *b;
} Type_1;

void function(Type_3 *type_3);

#endif

The second header:

#ifndef HEADER2_H
#define HEADER2_H

struct Type_1;

typedef struct {
    int a;
    char *b;
    struct Type_1 *c;
} Type_2;

typedef struct {
    int a;
    char *b;
    Type_2 *c;
} Type_3;


#endif

Upvotes: 1

Bechir
Bechir

Reputation: 1051

Move all your types definitions to one files and functions declarations to another one.

header1.h

#ifndef HEADER1_H
#define HEADER1_H
typedef struct {
  int a;
   char *b;
} Type_1;


typedef struct {
    int a;
    char *b;
    Type_1 *c;
} Type_2;

typedef struct {
    int a;
    char *b;
    Type_2 *c;
} Type_3;

#endif

header2.h

#ifndef HEADER2_H
#define HEADER2_H
#include "header1.h"


void function(Type_3 *type_3);

#endif

Upvotes: 0

Related Questions