where should “include” be put in C++

后端 未结 9 1973
生来不讨喜
生来不讨喜 2020-12-14 16:06

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

相关标签:
9条回答
  • 2020-12-14 16:19

    You would make all other files including your header file transitively include all the #includes in your header too.

    In C++ (as in C) #include is handled by the preprocessor by simply inserting all the text in the #included file in place of the #include statement. So with lots of #includes 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 #included! 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 #includes.

    0 讨论(0)
  • 2020-12-14 16:27

    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.

    0 讨论(0)
  • 2020-12-14 16:27

    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.

    0 讨论(0)
提交回复
热议问题