Dual enable solution?

In C ++, I have a double problem:

File stuffcollection.h

#pragma once #ifndef STUFFCOLLECTION_H #define STUFFCOLLECTION_H #include "Stage.h" class Stuffcollection { public: bool myfunc( Stage * stage ); }; #endif // STUFFCOLLECTION_H 

Stage.h file:

 #pragma once #ifndef STAGE_H #define STAGE_H #include "Stuffcollection.h" class Stage { // stuffcollection used in stage.cpp }; #endif // STAGE_H 

Compiler Error:

\Stuffcollection.h|(line were bool myfunc is declared)|error: 'Stage' has not been declared| ||=== Build finished: 1 errors, 0 warnings ===|

Can someone explain why this is happening and how it can be solved? I already use include guard and the pragma after the preprocessor directive, and it just doesn't work.

(If I remove #include "Stuffcollection.h" from stage.h and comment out the corresponding lines that use it in stage.cpp, the rest of my code works fine. It's really simple when the stuffcollection is at the stage that it suddenly stops working. )

PS: stage is just one example, I use stuffcollection in almost every other file, and every time I get this problem.

EDIT : I followed the suggestion, and now the problem is invalid use of incomplete type , i.e. while the answers given to solve the circular dependency problem, they do not solve the problem I'm dealing with, My problem continues to Circular dependencies / Incomplete types .

EDIT : both resolved.

+3
source share
3 answers

You have circular addiction . Use Forward Declaration in Stuffcollection.h

 #pragma once #ifndef STUFFCOLLECTION_H #define STUFFCOLLECTION_H //#include "Stage.h" //<------------------Don't Do This class Stage; //<------------------Do This class Stuffcollection { public: bool myfunc( Stage * stage ); }; #endif // STUFFCOLLECTION_H 

Justification:
You can use the forward declaration in the above snippet because Stuffcollection.h uses a pointer to Stage .

Explanation:
Using the forward declaration of the Stage class, the compiler does not know the composition of it and the members inside it, the compiler knows that Stage is type . Thus, Stage is an Incomplete type for the compiler. With incomplete types, you cannot create objects or do anything the compiler needs to know the Stage layout or more than the fact that Stage is just a type. Since pointers to all objects must have the same memory allocation, you can use a forward declaration by simply referring to Stage as a pointer.

You can use forward ads to overcome your circular addiction problems.

Further reading:
When to use forward ads?

+14
source

This is a circular addiction. Do not do them. This one you can solve by replacing #include "Stage.h" with stuffcollection.h with a direct Stage declaration (i.e. class Stage; ).

+5
source

Instead of #include you can use forward declarations, i.e. class Stage; and class Stuffcollection . It also has the advantage of reducing dependencies.

+3
source

All Articles