C++ 包含 .cpp 而不是 header(.h)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9253786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Include .cpp instead of header(.h)
提问by sysop
There are some cases when we include .cpp file instead of standard header file (.h), for example:
在某些情况下,我们包含 .cpp 文件而不是标准头文件 (.h),例如:
#include "example.cpp"
instead of
代替
#include "example.h"
It seems to work but is this safe or should I avoid it?
它似乎有效,但这是安全的还是应该避免它?
What about the compilation time?
编译时间呢?
采纳答案by zellio
It's lazy coding. Use header files. Yes they can increase compile time but they mean that you can easily re-implement chunks of your code, or better yet, another developer could at anytime. The header file serves as a template for what your C/C++
code is going to do. It's a bad idea to discard or ignore it.
这是懒惰的编码。使用头文件。是的,它们可以增加编译时间,但它们意味着您可以轻松地重新实现代码块,或者更好的是,其他开发人员可以随时重新实现。头文件用作您的C/C++
代码将要执行的操作的模板。丢弃或忽略它是一个坏主意。
回答by Dan K
I agree with Kerrek SB.
我同意 Kerrek SB。
I did this once. I was building an excellent, widely used compression library that needed to be built separately for 8-bit images and for 12-bit images. The cleanest way I could come up with to fit this into the build system was (oversimplifying a bit) to have two master .cpp files, one that set #defines for an 8-bit build, the other for a 12-bit build. The master .cpp files then #included the source files of the compression library.
我做过一次。我正在构建一个优秀的、广泛使用的压缩库,需要为 8 位图像和 12 位图像分别构建。我能想出的最简洁的方法是(稍微简化一点)有两个主 .cpp 文件,一个为 8 位构建设置 #defines,另一个为 12 位构建设置。主 .cpp 文件然后 #included 压缩库的源文件。
It's okay to not follow a general rule if you understand the rule well enough to know the reasons for it and why it might not apply in your case. (But those cases ought to be rare.)
如果您对规则有足够的了解,知道它的原因以及为什么它可能不适用于您的情况,那么不遵循一般规则是可以的。(但这些情况应该很少见。)
回答by Dima Tisnek
There are legitimate uses for #include "impl.cpp"
:
有合法用途#include "impl.cpp"
:
testing for access to static/etc variables
ad hoc templates like these if c++ template mechanism proves inadequate (rare)
#define MACRO (...)
#include "impl.cpp" // uses MACRO
测试对静态/等变量的访问
如果 C++ 模板机制证明不足,则像这样的临时模板(罕见)
#define MACRO (...)
#include "impl.cpp" // uses MACRO
Note that #include "impl.cpp"
can be unsafe it same file is included in separate compilation units that are later linked together.
请注意,#include "impl.cpp"
将同一文件包含在稍后链接在一起的单独编译单元中可能是不安全的。
回答by Joqus
I have used it before and had no problem but I cannot ensure that this is safe. Sometimes this was the only option for me so I used it, otherwise I will use the .h file.
我以前用过它,没有问题,但我不能确保这是安全的。有时这是我唯一的选择,所以我使用它,否则我将使用 .h 文件。