Should I repeat inclusions in .cpp and .h?

Scenario:

foo.h:

#include <vector> class foo { public: std::vector<int>* getVector(); /* ... other methods declarations ... */ } 

foo.cpp:

 #include "foo.h" #include <vector> /* ... other methods definitions using std::vector ... */ std::vector<int>* foo::getVector() { return new std::vector<int>(); } 

I want .cpp to be independent of any possible future changes to the header. If for some reason the interface of the class changes and the dependency on <vector> can be removed, I risk that other methods in .cpp will also lose this inclusion.

Is it correct to repeat the inclusion of <vector> in .cpp and .h? Does this practice make sense or should I just rely on the inclusions made in the title?

+6
source share
4 answers

Include what you need and nothing more.

Including the same header file in multiple .h files and multiple .cpp files is not a problem in itself. Header protectors are effective in alleviating the problems of including files several times.

If you try to avoid including the same file several times, this can be negative, as this usually results in a β€œmega-inclusion file” that includes everything you need in the whole project. This is bad because a single change in any header file forces everyone to recompile.

If you are worried about the .h / .cpp file, including the same file, follow these guidelines:

  • If you do not need to include a header in the file, include it only in CPP
  • If a class declaration is required in the header file (but not used), use the formatted declaration in the .h file and include it in the CPP file.
  • If you really use include in the header file, include it in the header file, not CPP.
+15
source

No, not worth it. This is not practical. Redundant lines are worthless.

Each file should contain what it needs, and nothing more. In your particular case of the header and its implementation, a redundant declaration in .cpp does not help. If the title has changed so much that the function is no longer needed to return the vector, you still have to reevaluate .cpp.

+1
source

In the .cpp file, it’s enough to include only specific things for implementation (some kind of .cpp file actually), without repeating the things that you already included in the header. That way, when someone looks at your code, they also get a better and clearer picture of your code.

It can be very useful to know which dependencies are specific only for implementation, for example, when you update / replace it with another one (while saving the interface).

+1
source

Include as few files as possible in the header and include them only in the .cpp files they need. Your foo.h header file can be included in many other .cpp files that do not need declarations from other header files (in this case vector.h), which ultimately lead to longer compilations and less clear code.

+1
source

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


All Articles