I\'m reading some c++ code and Notice that there are "#include" both in the header files and .cpp files . I guess if I move all the "#include" in the fi
You would make all other files including your header file transitively include all the #include
s in your header too.
In C++ (as in C) #include
is handled by the preprocessor by simply inserting all the text in the #include
d file in place of the #include
statement. So with lots of #include
s you can literally boast the size of your compilable file to hundreds of kilobytes - and the compiler needs to parse all this for every single file. Note that the same file included in different places must be reparsed again in every single place where it is #include
d! This can slow down the compilation to a crawl.
If you need to declare (but not define) things in your header, use forward declaration instead of #include
s.
While a header file should include only what it needs, "what it needs" is more fluid than you might think, and is dependent on the purpose to which you put the header. What I mean by this is that some headers are actually interface documents for libraries or other code. In those cases, the headers must include (and probably #include) everything another developer will need in order to correctly use your library.
There's nothing wrong with using #include in a header file. It is a very common practice, you don't want to burden a user a library with also remembering what other obscure headers are needed.
A standard example is #include <vector>
. Gets you the vector class. And a raft of internal CRT header files that are needed to compile the vector class properly, stuff you really don't need nor want to know about.