PDA

View Full Version : Include issue



Platoon
6th October 2009, 10:08
Hi. I have a short test program and i need help concerning include files.
here is the code:



#ifndef CPROTOCOL_H
#define CPROTOCOL_H

#include "cpacket.h"

class CProtocol
{
private:
CPacket *mPacketList;

public:
CProtocol();
};

#endif // CPROTOCOL_H

#ifndef CPACKET_H
#define CPACKET_H

#include "cprotocol.h"

class CPacket
{
private:
CProtocol *parent;

public:
CPacket();
};

#endif // CPACKET_H



The compiler exits with return value 2 and says "In file included from cprotocol.h:4,"

I know that it has something to do with the recursive including of the two files but i think the #ifndef should prevent this.....
i hope someone can tell me what i'm doing wrong

scascio
6th October 2009, 10:18
You have to use forward declaration.

The compiler read cprotocol.h,
then cpacket.h through include directive,
then cprotocol again through include directive, but skip it because of #ifndef
then read CPacket definition and CPtrotocol is not defined!

Just declare the class without defining it instead of #include directive:


#ifndef CPROTOCOL_H
#define CPROTOCOL_H

class CPacket; //forward declaration
class CProtocol
{
private:
CPacket *mPacketList;

public:
CProtocol();
};

#endif // CPROTOCOL_H


#ifndef CPACKET_H
#define CPACKET_H

class CProtocol; //forward declaration
class CPacket
{
private:
CProtocol *parent;

public:
CPacket();
};

#endif // CPACKET_H

Platoon
6th October 2009, 10:28
Thank you for the fast help....this works fine and now i will always make forward declarations in headers. :o