Connecting Tech Pros Worldwide Help | Site Map

did any body know how to cross include head files?

  #1  
Old July 19th, 2005, 04:16 PM
George Zhou
Guest
 
Posts: n/a
Such as in a.h, I need put #include "b.h", while in b.h, I need put #include
"a.h", but it does not work! Any alternative way to do it?



  #2  
Old July 19th, 2005, 04:16 PM
John Harrison
Guest
 
Posts: n/a

re: did any body know how to cross include head files?



"George Zhou" <zhzhou@udel.edu> wrote in message
news:bekhjm$qaj$1@news.udel.edu...[color=blue]
> Such as in a.h, I need put #include "b.h", while in b.h, I need put[/color]
#include[color=blue]
> "a.h", but it does not work! Any alternative way to do it?
>[/color]

Include guards.

#ifndef A_H
#define A_H

// this is a.h

#endif

#ifndef B_H
#define B_H

// this is b.h

#endif

Might not be what you need, but its the answer to your question.

john


  #3  
Old July 19th, 2005, 04:17 PM
MiniDisc_2k2
Guest
 
Posts: n/a

re: did any body know how to cross include head files?



"George Zhou" <zhzhou@udel.edu> wrote in message
news:bekhjm$qaj$1@news.udel.edu...[color=blue]
> Such as in a.h, I need put #include "b.h", while in b.h, I need put[/color]
#include[color=blue]
> "a.h", but it does not work! Any alternative way to do it?
>
>
>[/color]

I've had this problem before. Something like this:

// a.h
#include "b.h"
class A
{
public:
A();
A(B& data);
int var;
};


// b.h
#include "a.h"
class B
{
public:
B();
B(A& data);
int var;
};

As you can see, both classes need each other's files. You cannot do this,
either you'll be using an endless loop or you'll be smart and use what John
told you to do. Either way, however, one of the files isn't going to have
access to the other's data. So what you need to do is declare, but not
define the information:

// a.h
class B; // declaration

class A
{
public:
A();
A(B& data);
int var;
};

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

class B
{
public:
B();
B(A& data);
int var;
};

This will work. I always put a

#pragma once

in my header files, but not all compilers support that. They function
exactly the same way as what John told you to do, it's just less coding.
It's a good idea, it'll protect you from including files more than once (and
then getting a billion redefinition errors).

--
MiniDisc_2k2
To reply, replace nospam.com with cox dot net.



Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
comp.lang.c Answers to Frequently Asked Questions (FAQ List) Steve Summit answers 0 November 14th, 2005 04:15 AM
comp.lang.c Answers to Frequently Asked Questions (FAQ List) Steve Summit answers 0 November 13th, 2005 11:37 PM
comp.lang.c Answers to Frequently Asked Questions (FAQ List) Steve Summit answers 0 November 13th, 2005 09:56 PM
comp.lang.c Answers to Frequently Asked Questions (FAQ List) Steve Summit answers 0 November 13th, 2005 03:15 AM