0

In C++, I have A.h and B.h. I need to include A.h in B.h, then I needed to use an object from B inside A.cpp. So I included B.h in A.h so it refused. I tried to use these lines in .H files

#ifndef A_H
#define A_H
...my code
#endif

I had the same refused. so I tried in A.h file to put

class B;

as a defined class. so it took it as another class not the same B class which i want. what i have to do?

Dan McClain
  • 11,780
  • 9
  • 47
  • 67
soufi
  • 1
  • 1
  • See also: http://stackoverflow.com/questions/4889462/cyclic-dependency-headers-and-templates – phooji Mar 11 '11 at 22:54
  • Sorry, you description is a bit confusing. Posting the sample code of all files would help. – Mahesh Mar 11 '11 at 22:58
  • Please use punctuation and proper capitalization in your questions. If you can't bother to take the time to communicate clearly, why would you expect people here to take the time to answer clearly? – Jim Balter Mar 12 '11 at 00:11

3 Answers3

2

See this FAQ

NNN
  • 386
  • 1
  • 9
1

You cannot include A.h in B.h and also include B.h in A.h - it is a circular dependency.

If a structure or function in A need to reference a pointer to a structure in B (and vice-versa) you could just declare the structures without defining them.

In A.h:

 #ifndef __A_H__
 #define __A_H__

 struct DefinedInB;

 struct DefinedInA
 {
     DefinedInB* aB;
 };

 void func1(DefinedInA* a, DefinedInB* b);

 #endif __A_H__

In B.h:

 #ifndef __B_H__
 #define __B_H__

 struct DefinedInA;

 struct DefinedInB
 {
     DefinedInA* anA;
 };

 void func2(DefinedInA* a, DefinedInB* b);

 #endif __B_H__

You can do this only with pointers, again to avoid the circular dependency.

florin
  • 13,986
  • 6
  • 46
  • 47
0

In general, it is better to avoid circular references, but if you need them in your design, and your dependencies are as follows:

a.h <-- b.h <-- a.cpp (where x <-- y represents "y" depends on "x")

Just type that in:

// A.h
#ifndef A_HEADER
#define A_HEADER
...
#endif

// B.h
#ifndef B_HEADER
#define B_HEADER
#include "A.h"
...
#endif

// A.cpp
#include "A.h"
#include "B.h"
// use contents from both A.h and B.h
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489