Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should I include a header that is already included via other headers?

Tags:

c++

header

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.

like image 348
aLostMonkey Avatar asked Oct 15 '10 20:10

aLostMonkey


People also ask

Should header files include other header files?

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.

What happens if a header file is included twice?

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.

Can you include a header in a header?

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.

Can you use header files twice in a program?

Note: We can't include the same header file twice in any program.


2 Answers

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>.

like image 50
James McNellis Avatar answered Oct 26 '22 22:10

James McNellis


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.

like image 22
TreDubZedd Avatar answered Oct 26 '22 22:10

TreDubZedd