Reputation: 1259
I have a question regarding where to #include iosteam and vector? In the main.cpp, header.h or in the memberfunction.cpp? Seems I needed using namespace std in main.cpp but #include< functional > in the header file>. Is there any robust way to do it? Thanks!
Upvotes: 1
Views: 325
Reputation: 206636
Simple Rule:
Include the header file only in those files which need it.
If your source or header file does not use any constructs defined/declared in the header file then there is no need to include that header. Doing so only brings unnecessary code in to those translation units thereby corrupting the namespace and possibly increasing the compilation time.
Upvotes: 3
Reputation: 361
If you use vectors, or input/output streams in any way in your header.h
(for instance, parameters of that type etc.), then it is better to include iostream
and/or vector
there. If you use them only internally in your memberfunction.cpp
, include it there (it is of no use to the rest of the code).
Upvotes: 0
Reputation: 1
For readability reasons you want to include headers only in those translation units using them. So in a source code not using at all std::vector
template you would not #include <vector>
, hence you would put that include before your own #include "myheader.h"
However, you may want to decrease compilation time by pre-compiling the header.
As I explain in this answer, precompiled headers with GCC works only if all your program has one single header containing all the includes. For that reason you would want to have a single myheader.h
which is itself including <vector>
(even for the few compilation units not using it).
Pre-compilation of header files is compiler (and perhaps system) specific.
Upvotes: 1