Header files and include best practice

I have a quick question regarding header files, inclusions and good coding style. Suppose I have 2 classes with corresponding source and header files, and then the final source file, where main () is located.

Inside Foo.hpp, I have the following statements:

#include <string> #include <iostream> #include <exception> 

Now with Bar.hpp I have the following statements:

 #include "Foo.hpp" #include <string> 

And finally, with Myprogram.cpp, I have the following statements:

 #include "Bar.hpp" #include <string> #include <iostream> #include <exception> 

I know that the include statements in <> in Myprogram.cpp and Bar.hpp are not needed to compile and run the program, but what is the best practice or the right way to do something? Is there a reason why you do not explicitly include the necessary header files in each file?

+4
source share
2 answers

You must include all the necessary files in each file that they need. If MyProgram.cpp requires a string , enable it, and do not rely on it being included by Bar.hpp . There is no guarantee, after 2 weeks Bar.hpp will turn it on anyway, and then you will remain with compiler errors.

Pay attention to the necessary - i.e. make sure you really need to enable it when a direct ad is announced or even completely excluded.

Also note that some system headers may include others - with a few exceptions, there is no requirement. Therefore, if you need both <iostream> and <string> , enable both, even if you can only compile one of them.

The order in which incoming messages are displayed (the system includes the user vs) corresponds to the coding standard that you follow - consistency is more important than the choice itself.

+9
source

Include everything you need in each file , but do not include files that you do not need . Typically, it is the task of the included file to make sure that it is not included twice, using precompiler flags, etc.

For example, if you need Foo.cpp but not Foo.h , include it in Foo.cpp not in Foo.h If required in both, include in both.

Tangentially, as best practice, never use using directives in the header file. If you need, you can use using directives in implementation files (.cpp).

+2
source

Source: https://habr.com/ru/post/1469373/


All Articles