Is standard practice the same as derivation in the header and source file?

When working with say, the standard string class in C ++. Do you need to have #include<string> both the header and source file?

Can you not just #include<string> just in the header file?

+4
source share
3 answers

The inclusion in the header file may indicate a dependency at the class definition level (for example, you accept or return strings). In this case, you must include include in the header; however, if you use only strings in your implementation, you may need to include only the source file.

+6
source

Best practice is to include the header file individually in each header or source file that requires it.

Including the necessary headers indirectly through other header files gives you the disadvantage that when you pull out the included header from the source file at some point in the future, you may encounter unclear compilation errors due to the missing (indirectly included) header.

+3
source

The inclusion of the file is done by replacing the include directive with the contents of the included header file (in practice, this is probably not done by replacing in a text stream, but by a semantically equivalent operation).

This means that all files included in the header will be included in the files, including this header, so no, you do not need to include it twice.

However, there are many policies for including files, and choosing one of them is a matter of what you focus on and best practices than what you need to do.

For example, you can strive for completeness and include files whenever you use the characters defined in these files.

I also worked with a project (low-level, cross-platform C library), where the client code was responsible for including dependencies of the header files explicitly before including the header file. This was done in order to preserve explicitly dependent headers and eliminate / minimize (as far as possible) hidden dependency restrictions imposed by the library on clients.

In the end, it is up to you (and / or your team).

+1
source

All Articles