Sign in to follow this  

Cyclic header inclusion for gcc

Recommended Posts

I'm trying to compiler the following code // this is file class A.h #ifndef CLASS_A_H #define CLASS_A_H #include "classB.h" class classA { public: enum enumA { enumA1=0, enumA2 }; void Info(classB::enumB rEnum){}; }; #endif //this is file classB.h #ifndef CLASS_B_H #define CLASS_B_H #include "classA.h" class classB { public: enum enumB { enumB1=0, enumB2 }; void Info(classA::enumA rEnum){}; }; #endif //and that's the main file #include "classA.h" int main() { classA i; } When compiling this code, I get the following error In file included from classA.h:4, from myTest.cpp:1: classB.h:15: error: ‘classA’ has not been declared classB.h:15: error: expected ‘,’ or ‘...’ before ‘rEnum’ It seems, the problem is the cyclic inclusion of the headers, but I do not understand what the problem actually is. I could certainly define the enums in a different header, but I prefer to add them to the classes. Unfortunately, there is no forward declaration for enums, but since I'm using the enums as parameter of a method the header file has to be included. Any suggestions, why the compiler (gcc 4.4.1) is not able to compile that code

Share this post

Link to post
Share on other sites
Think about what the compiler is doing. Let's say it grabs classA.h first:

Ok, starting to compile:
Is CLASS_A_H defined? No... ok let's keep going
define CLASS_A_H. Done.

Include "classB.h" Ok, let's grab that file.

Is CLASS_B_H defined? No... ok let's keep going
define CLASS_B_H. Done.

Include "classA.h" Ok, let's grab that file.

Is CLASS_A_H defined? Yep, let's skip to the endif.

Hey this was an empty file. Let's go back to what we were doing in classB.h.

class classB Ok. I'm declaring a class.
void Info(classA::enumA rEnum){}; Hey, classA? What's that? I haven't seen that before!

So you see, you can't have cyclic dependencies like that. If at all possible, try to keep '#include's in your definition files, and just forward declare in your headers.

Also, you can forward declare enums.

enum myEnum; // <-- forward declaration.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this