My c++ program is using a separate header file (Let's call it myHeader.h) and therefore includes it (#include "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?
-
2Please can you explain the question a little more clearly.David Heffernan– David Heffernan2011-02-07 21:01:37 +00:00Commented Feb 7, 2011 at 21:01
-
1obviously, you watch too much Eretz Nehederet...Amir Rachum– Amir Rachum2011-02-07 21:05:55 +00:00Commented Feb 7, 2011 at 21:05
6 Answers
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.hin a header fileB.hwill also make any file that includesB.hincludeA.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).
1 Comment
.h files when they are explicitly required by the .h file. Also note EToreo's response that putting includes in your .h can cause increased build times (potentially MUCH longer build times).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.
Comments
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.
2 Comments
class blah; line which says this class exists, I will give you the details later - it saves having to include blah.h to use the classThere 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.