LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Circular Header files problem (https://www.linuxquestions.org/questions/programming-9/circular-header-files-problem-413606/)

allomeen 02-09-2006 06:37 PM

Circular Header files problem
 
Hello,

I have a problem and I don't know if there is any solution to it. I have three classes: Obj1, Obj2 and Obj3. Obj1 includes Obj2 and Obj2 includes Obj3, and Obj3 includes Obj1. for example:

//Obj1.h
#include "Obj2.h"

//Obj2.h
#include "Obj3.h"

//Obj3.h
#include "Obj1.h"

Whenever I compile, I get a lot of errors saying that Obj1 is not declared wherever I use Obj1. There are a circular dependency and I'm wondering is there any way i can solve this problem, without changing the structure of the program??

Thanks,
Alaa

dmail 02-09-2006 07:41 PM

use forward prototypes or include them in the same header/namespace (if this fits the design)

The_Nerd 02-09-2006 11:59 PM

Two ways:
(1):
Wrap each header file in an #ifndef, like so:
myheader.h:
Code:

#ifndef _MYHEADER_H_
#define _MYHEADER_H_

//Contents here

#endif
//EOF

This should solve most problems, and you should always do this, no matter what the situation.

The second way, which is sometimes needed, is to prototype the class, function, or datatype being used. Like so:
Code:


int MyFunc(int); // Prototype
class B; //Prototype

class A
{
    public:
        bool MyBool;
        B MyB;
};

class B //Declaration
{
    public:
        bool YetAnotherBool;
};

int main(int argc, char **argv) //Declaration
{
}

int MyFunc(int iI) //Declaration
{
    //Do something
}

Hope that helps. By the way, if you have a multi-file project, you might want to read up on the "extern" keyword.

allomeen 02-10-2006 11:34 AM

Thank you guys, I do have this in the header fils. The way i solved the problem is by moving some of the include header to the ".cpp" file so I don't get the circular definitions and it works beautifully.. Thanks anyway.

paulsm4 02-10-2006 01:44 PM

You should still do the "#if !defined(_MY_HEADER_H)" ...
 
regardless of whether or not you got past the immediate problem, The_nerd's advice is good advice - you should definitely do this with all of your headers.

IMHO ...

allomeen 02-11-2006 06:59 PM

I already have those in the header file. That was not the problem. The problem was where I define it. I had to define it in the .cpp file instead.

Thanks,
Alaa


All times are GMT -5. The time now is 06:28 AM.