Is an #include before #ifdef/#define Include-Guard okay?

ⅰ亾dé卋堺 提交于 2019-12-05 02:38:13

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.

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.)

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!