Circular Includes

Hi guys,

I have an include dependency tree that looks like the following:

https://drive.google.com/file/d/16OolfD0RIlWrVQx187-1LPtf_889-WNY/view?usp=sharing

From the looks of it, World includes BuildingActions, InformationActions, MovementActions , and BuildingActions, InformationActions, and MovementActions includes World.

My code compiles fine, but why? Generally, when I have Dep1.h includes Dep2.h and Dep2.h includes Dep1.h my program fails to compile.

I do have #include guards which could be helping, but that hasn't seemed to help in the past.

Basically, when it is valid to have circular includes and when does it result in a compilation error?
I think it's pretty much agreed upon that circular includes are to be avoided. In my personal experience they cause a lot of trouble and most of the time don't compile.

If you're dealing with classes, what you can do is a forward declaration.
And since we can't access your link, we can't tell you exactly why your code is compiling.
Last edited on
Perhaps you have some implicit "#pragma once" going on.
I do have #include guards
There's your answer.
but [include guards haven't] seemed to help in the past
There's your problem. So the question isn't "why is this working", it's "why weren't include guards working in the past? See my comment here for one possibility: http://www.cplusplus.com/forum/beginner/246867/


Circular includes should be avoided. When you include a header file, the compiler generally copies and pastes the content of a header file into the destination file. So you can imagine the mess you'd be creating if there are any circular includes present. If you're using MSVC, by default you should have a "#pragma once" pre-processor directive included in each header file. You don't have to write your own guards if using pragma once. I believe pragma once also works across many other C++ compilers.
#pragma once also works across many other C++ compilers.

Apparently, it's so ubiquitous that it might as well be standardized.

Besides not being part of C++, its primary disadvantage is that #pragma once has unclear semantics if source files have been copied around or symlinked. If you use include guards you're fine, but #pragma once might yield ODR violations.

IMO, the decision hardly matters. Maybe #pragma once is generally superior for most cases, but I still use include guards out of habit (my editor inserts them.)
Last edited on
Topic archived. No new replies allowed.