Archived

This topic is now archived and is closed to further replies.

WebsiteWill

#ifndef question

Recommended Posts

I'm getting some "already defined in" LNK2005 errors when I try to compile my code. The code consists of 3 .h files and 2 .cpp files. The .h files are all surrounded by #ifndef XXXX_X #define XXXX_X .........CODE HERE #endif However, if I #include any of the .h files in multiple other files then I still get LNK and redefinition errors. Obviously, I need to be able to include these files inside of multiple others. For instance. I have a network class in Net.cpp and Net.h Net.cpp #includes Net.h and the main program will also need to include Net.h but it's not letting me for some strange reason. I would post actual code but it's way too lengthy. Here is some basic code that's similar
//Packet.h

#ifndef PACKET_H
#define PACKET_H
class PacGeneric
{
  public:
    void PacCount();
  private:
    int iNumPacs;
};
void PacGeneric::PacCount()
{

}
#endif
   
//Net.h

#ifndef NET_H
#define NET_H
#include "Packet.h"
class Net
{
  public:
    void SomeFunc(); 
  private:
    PacGeneric myPacket;
};
#endif
   
//Net.cpp

#include "Net.h"
void Net::SomeFunc()
{
     code
}
//Main.cpp

#include "Net.h"
int main()
{
    Net myNet;
    return 0;
}
If I don't include Net.h inside of Main I get an error telling me that Net is not defined. If I do include Net.h I get many LNK errors telling me that all of the functions located in file Packet.h are already defined inside of Net.h Any ideas? I swear this should work...I feel like such a noob having to ask such a question. Webby [edited by - websitewill on August 9, 2003 4:59:36 PM]

Share this post


Link to post
Share on other sites
Try inlining the PacCount method



//Packet.h

#ifndef PACKET_H
#define PACKET_H
class PacGeneric
{
public:
void PacCount();
private:
int iNumPacs;
};
inline void PacGeneric::PacCount()
{

}
#endif


[edited by - en dum en on August 9, 2003 5:19:10 PM]

Share this post


Link to post
Share on other sites
dont include the header into your other header, just replace

#include "Packet.h"


with

class PackGeneric;


and add this

#include "Packet.h"


under this

#include "Net.h"


its called forward declaration

Share this post


Link to post
Share on other sites
quote:
Original post by honayboyz
dont include the header into your other header, just replace

#include "Packet.h"


with

class PackGeneric;


and add this

#include "Packet.h"


under this

#include "Net.h"


its called forward declaration




That won''t work here because he''s using an instance of the type in his class, not just an indirect reference to it. He has to do what was described instead, either move the member function definition to a cpp, or inline it (other wise the containing class would have no idea how much space each instance of its type would need because it doesn''t know anything about the type it''s aggregating.

Share this post


Link to post
Share on other sites