0

I'm trying to make some project in C.

I would like to know if it is possible to make #include from the same file twice, in a way that recalls diamond heritage.

i.e.

  • in a.c there is #include "a.h"
  • in b.c there is #include "b.h"
  • in b.h there is #include "a.h"

Is it possible to #include "b.h" in a.c?

I get an error:

some_variable already defined in a.obj
Gilles 'SO- stop being evil'
  • 98,216
  • 36
  • 202
  • 244
hudac
  • 2,258
  • 5
  • 28
  • 52

2 Answers2

6

Simple: don't define variables in headers, just declare them:

Header:

// a.h

#ifndef A_H             // always use #include guards
#define A_H

extern int my_variable; // declare my_variable

...

#endif

Source file a.c:

// a.c

#include "a.h"

int my_variable;        // define my_variable

...

Source file b.c:

// a.c

#include "a.h"
#include "b.h"

...

As others have mentioned, #include guards are useful, and a good habit to get into, but they are probably not the solution for this specific problem.

Paul R
  • 202,568
  • 34
  • 375
  • 539
2

You have to declare extern the variables in a.h, then modify your header a.h in the following way:

 #ifndef a_h
 #define a_h

   //your a.h 

 #endif
888
  • 3,067
  • 8
  • 36
  • 58