Problem with header file inclusions

I have a class Myclass (for the sake of the example). I have a header file 'space.h', which is following:

1
2
3
#include "Myclass.h"

struct Files {Myclass* new_object, int number};


But turns out in the Myclass.h, I need the struct Files, like so:

void function(vector<Files> arrangement);

So I would have to include "space.h" in the Myclass.h, but this way there's going to be a double definition of struct Files, since Myclass.h includes space.h and space.h includes Myclass.h. I haven't got a clue how I can make it work, so any advice?
Seeing as you are using a pointer to Myclass you can forward declare the Myclass class and leave the #include "Myclass.h" until the cpp source file:

1
2
3
class Myclass;

struct Files {Myclass* new_object, int number};


HTH
You use a header guard:

1
2
3
4
#ifndef included
#define included
// Code here
#endif 
Last edited on
Just to clarify, you have two problems here:

1) Multiple inclusion - the possibility of the same header file being included twice in the same translation unit (i.e. the same .cpp file).

This is fixed by the solution in Bourgond's post. Whenever you're writing a header file, you should ALWAYS do this. Only don't use "included" as the name of the symbol - the name has be unique to the header file. Normally, people include the name of the header file in the symbol, so, for example, if the file is MyClassA.h, you'd have;

1
2
3
4
#ifndef MYCLASSA_H_INCLUDED
#define MYCLASSA_H_INCLUDED
// Code here
#endif  


2) Recursive dependency - class A depends on class B, which depends on Class A.

This usually indicates your design isn't right. ajh32's post addresses this issue. In the code you posted, Files doesn't actually depend on the definition of MyClass, as it's only using a pointer to it. space.h therefore doesn't need to include MyClass.h - it just needs to forward-declare the MyClass is a class.
Last edited on
Ahh, that helps a lot.
Topic archived. No new replies allowed.