Cyclic header dependency

P

pallav

I have two header files, circuit.h and latch.h that reference each
other and are causing a cyclic dependency.

latch.h file

#include "circuit.h"
typedef boost::shared_ptr<struct Latch> LatchPtr;

class Latch
{
...
CircuitPtr circuit;
};

circuit.h file

#include "latch.h"
typedef boost::shared_ptr<struct Circuit> CircuitPtr;

class Circuit
{
...
list<LatchPtr> latches;
};

As you can see there is a cyclic dependency. To get things to compile,
what I've done is
I've changed the circuit.h file as follows:

new circuit.h file

// defined in latch.h, can't do #include "latch.h" as that will
introduce cyclic dependency
extern typedef boost::shared_ptr<struct Latch> LatchPtr;

typedef boost::shared_ptr<struct Circuit> CircuitPtr;

class Circuit
{
...
list<LatchPtr> latches;
};

This solves the problem, but I'm wondering if this is the way to fix
such issues. I know C++ has forward declarations but I"m still trying
to figure out how to use them and if they'll solve this. The other
option is to combine the two header files but I would prefer not to do
that.

Is the above fix bad practice? thanks for your time.
 
J

jichao06

I have two header files, circuit.h and latch.h that reference each
other and are causing a cyclic dependency.

latch.h file

#include "circuit.h"
typedef boost::shared_ptr<struct Latch> LatchPtr;

class Latch
{
...
CircuitPtr circuit;

};

circuit.h file

#include "latch.h"
typedef boost::shared_ptr<struct Circuit> CircuitPtr;

class Circuit
{
...
list<LatchPtr> latches;

};

As you can see there is a cyclic dependency. To get things to compile,
what I've done is
I've changed the circuit.h file as follows:

new circuit.h file

// defined in latch.h, can't do #include "latch.h" as that will
introduce cyclic dependency
extern typedef boost::shared_ptr<struct Latch> LatchPtr;

typedef boost::shared_ptr<struct Circuit> CircuitPtr;

class Circuit
{
...
list<LatchPtr> latches;

};

This solves the problem, but I'm wondering if this is the way to fix
such issues. I know C++ has forward declarations but I"m still trying
to figure out how to use them and if they'll solve this. The other
option is to combine the two header files but I would prefer not to do
that.

Is the above fix bad practice? thanks for your time.




I didn't go through the detail of your code. However, I think what you
need in the header file is only a pointer, which does not make it
necessary to include the header file to introduce the name. You can
use forward declaration in header file and include the header file in
the source file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top