0

I'm not 100% on how the compiler reads header files, so I wanted to know why this gives a compiler error and doesn't work:

#ifndef FOO_H
#define FOO_H

#include "central.h"

class Foo
{
  Oof var;
}

#endif
#ifndef OOF_H
#define OOF_H

#include "central.h"

class Oof {}
#ifndef CENTRAL_H
#define CENTRAL_H

#include "foo.h"
#include "oof.h"

When compiled it gives the error that "oof does not name a type." My best guess is that it's because they continue including each other?

Other than that, is just doing #include "oof.h" in Foo the only/best way to do what I'm trying to do here?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • The compiler reads header files by literally pasting them in place of the `#include` line. More specifically, the preprocessor does this before the compiler even gets to see it. – mkrieger1 Apr 23 '21 at 19:26
  • You seem to have two cyclic include dependencies here, is this intentional? – mkrieger1 Apr 23 '21 at 19:31
  • As far as I can tell you should not include central.h in neither foo.h nor oof.h. – mkrieger1 Apr 23 '21 at 19:32
  • @mkrieger1 I do have them including each other, didn't know it had a name though. So you can't have cyclical dependencies. In other words, if foo needs any include paths it has to have it's own include statements in it's own header, and can't depend on central.h include paths. – Kincaid Nichols Apr 23 '21 at 20:02
  • Is that right? Following that though, does central.h need to have things like #include if foo or oof have it already? And if it doesn't, is it good practice to not do it or to put it in there anyway for clarity? – Kincaid Nichols Apr 23 '21 at 20:03
  • `central.h` doesn't seem like a good idea to begin with. Is the idea that you have one single "everything I need to include" file that you include everywhere else? That's going to create more headaches than it solves compared to just including the files that you actually use each place you use them. – Nathan Pierson Apr 23 '21 at 21:22
  • @NathanPierson 'central.h' is more functions.h than anything. I eventually came to the same conclusion, that even if what I did were possible it would still be better to just rewrite the include files in the headers that use them for claritys sake if nothing else – Kincaid Nichols Apr 25 '21 at 22:01

0 Answers0