开发者

Does it matter whether I put an #include directive in my cpp file or in an included header file?

My c++ program is using a separate header file (Let's call it myHeader.h) and therefore includes it (#in开发者_StackOverflow社区clude "myHeader.h"). In my program I need to use another header file (Let's call it another.h). Does it make a difference whether I put the #include "another.h" directive in the cpp file or in myHeader.h?


If it's not used in the .h file, then there will be no difference in compilation success/failure.

However, it is recommended to put include for header files you only need in the implementation in the .cpp files for the following reasons:

  • for encapsulation reasons - no one needs to know what you include solely for the implementation.
  • Including a file A.h in a header file B.h will also make any file that includes B.h include A.h. That can cause major dependency issues between seemingly unrelated files.
  • for the above reason, it can also increase build time substantially (every file you include is copied in your compilation unit).


If you need to include a header only in your cpp file then you should include it in your cpp file.

If you include it in your header it will add unneeded dependencies for everyone else who includes your header. This can explode if the unneeded headers you include also include other unneeded headers of their own.


The answer to your question is "No". However, you should try to avoid making unnecessary include statements in your .h files because it will induce longer build times. It is also better for encapsulation reasons as well.


Assuming all your include guards are in place etc then no.

It's best to think of how the user will use the code and try and avoid surprises for them.

In general you should avoid complex trees of include files included form other include files - although precompiled headers on modern compilers help.

BUT you should also make sure that you have all the advanced declarations in place so that the order of includes in a cpp file doesn't matter.


No difference really. Header files and cpp files can both include other files. The included files are effectively copied into the text stream.


There is a difference - every time your h file is included, any files included in that h file are included as well - I haven't kept up-to-date with modern C++ compilers, but this used to really increase compile time.

It also increases the physical dependency of the source - John Lakos' Large Scale C++ Software Design addresses this, and is well worth a read on structuring c++ programs. It's published in 1996, so it's not based around current practice, but the advise on structure is worth knowing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜