user1994405
user1994405

Reputation: 67

Extern typedefs in C

I have 4 files:

a.h:

typedef struct {
    int a;
} A;

b.h:

#include "a.h"
typedef struct {
    A a;
    int b;
} B;

c.h:

#include "a.h"
typedef struct {
    A a;
    double c;
} C;

d.c:

#include "b.h"
#include "c.h"
//Here I want to use types A, B and C

int and double are only examples, the real problem I have is far more complex.
The point is that it should be possible to convert types B and C to A by simply casting to it.
The issue I´m fighting is that it says type A is included multiple times, which is comprehensible because d.c includes b.h which includes a.h, but a.h is also included by c.h.
Is there a way to do that?

Upvotes: 2

Views: 7489

Answers (2)

pmg
pmg

Reputation: 108978

a.h

#ifndef A_H_INCLUDED
#define A_H_INCLUDED
typedef struct {
    int a;
} A;
#endif

b.h

#ifndef B_H_INCLUDED
#define B_H_INCLUDED
#include "a.h"
typedef struct {
    A a;
    int b;
} B;
#endif

c.h

#ifndef C_H_INCLUDED
#define C_H_INCLUDED
#include "a.h"
typedef struct {
    A a;
    double c;
} C;
#endif

d.c

#include "a.h" // if you're going to use type A specifically do #include the proper file
#include "b.h"
#include "c.h"
//Here I want to use types A, B and C

Upvotes: 4

Gereon
Gereon

Reputation: 17874

Use include guards, like so:

#ifndef A_INCLUDED
#define A_INCLUDED
typedef struct {
  int a;
} A;
#endif

in each of your .h file, with unique guard names per file

Upvotes: 3

Related Questions