-
#include
I have a header file, Classes.h, and another header file, Functions.h.
Theres two classes in Classes.h, and one function in Functions.h. Class A needs to pass a reference to class B to the function in Functions.h. Now classes.h needs to include functions.h so it knows recognizes the function name, but functions.h needs to include classes.h because it needs to recognize the class that is being passed to it. But if you include functions.h in classes.h and classes.h in functions.h, you get an infinite recursion error. I have tried including classes.h and function.h in the main cpp file, but that doesn't work. how can i solve this?
-
Put header guarding in both .h files. Don't put any code into those files, they only contain either template functions, or prototypes. You might need a Functions.cpp file as well.
-
-
Header gaurding looks like this:
Code:
#ifndef INCLUDED_MY_PROJECT_CLASSES_H
#define INCLUDED_MY_PROJECT_CLASSES_H
// Classes.h code here...
#endif
The first time the header is included INCLUDED_MY_PROJECT_CLASSES_H will not yet be defined, so the code gets compiled. If the header is included a second time, INCLUDED_MY_PROJECT_CLASSES_H is already defined, so everything between the #ifndef and the #endif is ignored.
Also, make sure that each header defines a different name.
-
I still can't get it to work. I've done this:
Main.cpp:
#include "Classes.h";
Classes.h (header gaurded):
#include "Functions.h";
Functions.h (not header gaurded):
#include "Classes.h";
I don't get the recursion error, but Functions doesn't recognize anything in Classes, and vice versa. Please tell me what i'm doing wrong.
thanks
-
Functions.h needs the code from Classes.h, but that code comes after the #include of Funcions.h.
The problem is that Classes.h needs Functions.h, and Functions.h needs Classes.h. The only solution for this problem is that you change the design of your code files. If for example Classes.h only needs some part of Functions.h, which in turn does not need Classes.h, you could put that part of the code in a separate file, BasicFunctions.h:
Code:
BasicFunctions.h
// Some functions
Classes.h
#include "BasicFunctions.h"
// Some classes
Functions.h
#include "Classes.h"
// Some functions
It's also posible that you put function implementations in your header files. You shouldn't do that, implementations should go into .cpp files. Put only declarations in headers.
-
If you only need a reference in the functions.h header you can add a forward declaration for the class:
class B;
void func(B &rb);