14

I always placed my #include after the #ifdef/#define Include-Guard. Now the refactor mechanism of my IDE (Qt Creator) put it before the Include-Guard e.g.

#include "AnotherHeader.h"

#ifndef MYHEADER_H
#define MYHEADER_H

Can this cause any problems or can I leave it this way?

4
  • Just make sure you have include guards inside "AnotherHeader.h" as well, if it is yours. Commented Jan 8, 2014 at 6:48
  • 2
    This question does not seem to have anything to do with the qt tag, so removing it. Commented Jan 8, 2014 at 6:54
  • 1
    Even if this compiles, every reader of your code will wonder why you include files before the guards. You should only commit such code if it's common pratice in your team.
    – hansmaad
    Commented Jan 8, 2014 at 8:04
  • Curious. I wonder why Qt Creator did this. Commented Feb 18, 2015 at 12:24

3 Answers 3

12

If the header in question has include guards itself, you won't run into problems. Putting it inside the include guards may still speed up compilation. Something the compiler does not see takes less time to compile, even if it does not produce any errors.

1
  • IIRC, GCC detects the header guard pattern and would exclude further duplicate includes. However, doing something like what the OP had done would likely break it, nullifying the compilation speed improvement. Commented Jan 8, 2014 at 6:52
6

Although less common, I believe this is considered to be acceptable, however beware: if you have circular #include's, your includes will typically include each other forever (until the pre-parser complains about the maximum include depth being reached). This will not happen with the #include's after the include guards.

(Circular #include's is not considered good style in any case, but if it is used nevertheless, it might work with #include's after the include guards, but certainly won't with the #include's before them.)

1
  • 1
    Which is why I recommend putting them OUTSIDE of the include guards, since that way you will know if you create circular #include's.
    – yyny
    Commented Oct 24, 2015 at 20:42
3

Simply check out, what will happen. Let's assume, that two different headers uses MyHeader.h.

  1. AnotherHeader.h is included unconditionally
  2. Include guard allows loading rest of your header file.

The next time:

  1. AnotherHeader.h is included unconditionally again
  2. Include guard prevents from loading rest of your header file.

If AnotherHeader.h is include-guarded, nothing bad should happen. But generally I'd put the include-guard at the top of your file - there's no point in loading AnotherHeader.h again, when it was already loaded once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.