Why #include<.hpp> in .cpp, not <.cpp> in .hpp?

This question already has an answer here:

  • How does the compilation/linking process work? 5 answers
  • Why have header files and .cpp files? [closed] 9 answers

  • You can #include arbitrary files in a C++ translation unit (the *.cpp you are compiling) provided the preprocessed form (after pre-processing) is valid C++. Read some documentation on the preprocessor and the C preprocessor wikipage. Don't forget that preprocessing is the first phase in a C or C++ compiler. (Historically, it was even a different process /lib/cpp ; now it is inside the compiler for performance reasons).

    The name of the included file does not matter much. Conventionally, you don't want to name an included file to look like a top-level translation unit. This is why people generally do not #include "example.cpp" but something like eg #include "example.inc" or #include "example-inc.cpp" (or #include "example.def" , specially if you #include several times a header). The standard C++ library accepts #include <map> for example.

    See for example this answer which shows some included file which is #include -d several times (for different purposes), or, inside the GCC source tree, the file gcc/tree.def

    Of course, you cannot #include several times an arbitrary C++ file in the same compilation unit (because you cannot have several definitions of eg the same function).

    In practice, use eg g++ -C -E foo.cc > foo.ii to get the pre-processed form of translation unit foo.cc ... then look with a pager or editor into the preprocessed form foo.ii

    Read also about some proposal on modules in C++. It was not accepted in the latest C++ standard, but something similar might perhaps become standardized in the future.

    链接地址: http://www.djcxy.com/p/73300.html

    上一篇: 图书馆如何在编译和链接时间工作

    下一篇: 为什么在.cpp中包含<.hpp>,而不是在.hpp中包含<.cpp>?