H
H
Hatemylifezxc2020-06-10 14:00:14
C++ / C#
Hatemylifezxc, 2020-06-10 14:00:14

Where, in terms of structure, should I write #include in .h files, or in .cpp?

Let's say there is a Header.h file and a corresponding Header.cpp file with definitions.
I used to think that the most structured convenient and understandable code is obtained if only the project files that are written in quotes #inlcude "" are included in the header, and in the cpp file the only include with such quotes is the corresponding header file with declarations. So a person who reads the code can, without looking into the implementation code, look at the header and understand the relationships.
In the cpp file, you only need to include library files #include <>, so when writing an implementation, for example, if you need std::map at the top of the file, immediately write the necessary include, plus in some environments this is done automatically, just write std::map.
BUT let's say functions with types that are defined in the library are declared in the header? What to do then ?
You still have to include the libraries in the header file.
Or, for example, it can be convenient to show the implementation of some small functions right in the header.
It turns out that there is no way to get rid of the confusion and the library inclusions will be both in the header and in the cpp file?
whether it is necessary to duplicate in that case inclusions?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2020-06-10
@Hatemylifezxc

The main thing to follow when placing includes is the principle of the greatest closeness - as few entities as possible should stick out in the *.h file.
For example, for placing in *.h file matyuk type using namespace std; the poster is threatened with an unpleasant scrutiny at the code review with a verdict REMOVED DOWN
Because such a posting leads to a global pollution of the namespace with terrible consequences.
Thus, the fewer different kinds of includes stuffed into the header, the better. This speeds up compilation somewhat, since the compiler has to parse less, and also reduces the clutter of the global namespace with declarations.
For example, if you have a pointer to some other class in your class, you don’t need to drag the include of this class, it’s enough to make a forward declaration.
"Understanding relationships" allows the IDE. There you can see what's included.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question