0

I have 2 files that use each other in them, so I try to include each of them in each file, which doesn't work because the files would include themselves. I tried putting the relevant include statements inside the header guards, but that makes the compiler think that all the variable names are type identifiers.

Here's what I have when its inside the header guards

//MenuItem.h
#include <SDL.h>
#include <string>

#ifndef MENU_ITEM_H  //avoid multiple inclusion
#define MENU_ITEM_H

#include "window.h"
class MenuItem {
    bool selected = false;
    window containerWindow;
    etc

Window.h includes MenuItem.h within it's header guards.

In MenuItem.h I get errors such as

Error   1   error C2146: syntax error : missing ';' before identifier 'containerWindow' 
Error   2   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int   

When I have them outside the head guards (like so)

//MenuItem.h
#include <SDL.h>
#include <string>
#include "window.h"

#ifndef MENU_ITEM_H  //avoid multiple inclusion
#define MENU_ITEM_H

class MenuItem {
    bool selected = false;
    window containerWindow;
    etc

I get the following

Error   1   error C1014: too many include files : depth = 1024

I'm unsure how I can fix it.

Matt
  • 49
  • 1
  • 8

1 Answers1

1

Avoid circular inclusion by using forward declaration: use a window pointer in your class MenuItem instead of an object.

Replace:

#include "window.h"
class MenuItem {
    bool selected = false;
    window containerWindow;
    etc

By:

class window; // or struct window if window is a struct
class MenuItem {
    bool selected = false;
    window* containerWindow;
    etc

Also, as commented, make sure you #ifdef has a #endif, but I don't think that was causing the problem you reported.

jpo38
  • 20,821
  • 10
  • 70
  • 151
  • Thanks a lot! That got it to work! I had tried using a forward declaration but that didn't work, I wasn't using a pointer though. I assume it works because you don't need to know what the default constructor is when initializing a pointer, correct? – Matt Dec 28 '14 at 15:36
  • It works with pointers because compiler does not need to know the actual size of the object (compiler knows the size of a pointer, it depends on your targetted platform, but does not know the size of a Window object...unless header file is included). – jpo38 Dec 28 '14 at 15:47
  • PLease also vote up if it fixed your problem. Thanks. – jpo38 Dec 28 '14 at 15:48
  • Don't have enough reputation to upvote, have enough reputation to do so. Would if I could – Matt Dec 28 '14 at 16:24