I had only just noticed my programs using the string class were compiling without including the <string>
header. It turns out that <iostream>
includes <ios_base>
which in turn includes <string>
.
Is this bad practice and should I explicitly include <string>
? Even if it's just a case of clarity?
Is it safe to assume this applies to more than just the <string>
header? Perhaps this is implementation specific and or does the standard state the <string>
header be included via <ios_base>
and <iostream>
? Ensuring that any respected and widely used implementation will always include <string>
providing the the call to <iostream>
exists.
Header File Inclusion RulesA header file should be included only when a forward declaration would not do the job. The header file should be so designed that the order of header file inclusion is not important. The header file inclusion mechanism should be tolerant to duplicate header file inclusions.
When a header file is included two times in a C program, the second one gets ignored. In actual, the #, called the include, preceding a header file ensures that it is included only once during the compilation process.
Show activity on this post. Yes, this will work. Note, however, that if you include a lot of headers in this file and don't need all of them in each of your source files, it will likely increase your compilation time.
Note: We can't include the same header file twice in any program.
You should explicitly include whatever standard library headers you need.
It is not specified which standard library headers are included by other standard library headers, so such details will differ between compilers.
One case where you can rely on a header being included by another header is if a class in one header derives from a class in another. For example, <iostream>
has to include <ios_base>
because classes defined in <iostream>
are derived from classes defined in <ios_base>
.
A good practice is to always include the headers for the classes you'll be using in a given source file, regardless of whether you "know" they're included by already-included files.
If, while refactoring your code, you remove the necessity for one of the higher-level included files (iostream, for example), it could become quite painful to determine why your application no longer compiles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With