包含 .cpp 而不是 header(.h)
在某些情况下,我们包含 .cpp 文件而不是标准头文件 (.h),例如:
#include "example.cpp"
而不是
#include "example.h"
它似乎可以工作,但这安全吗还是我应该避免它?
编译时间怎么样?
There are some cases when we include .cpp file instead of standard header file (.h), for example:
#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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是懒惰的编码。使用头文件。是的,它们可以增加编译时间,但它们意味着您可以轻松地重新实现代码块,或者更好的是,其他开发人员可以随时重新实现。头文件充当
C/C++
代码将要执行的操作的模板。丢弃或忽略它是一个坏主意。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.我同意 Kerrek SB 的观点。
我这样做过一次。我正在构建一个优秀的、广泛使用的压缩库,需要分别为 8 位图像和 12 位图像构建。我能想到的将其融入构建系统的最干净的方法是(稍微简化了一点)有两个主 .cpp 文件,一个为 8 位构建设置 #defines,另一个为 12 位构建设置 #defines。主 .cpp 文件然后#included 压缩库的源文件。
如果您足够了解规则并知道其原因以及为什么它可能不适用于您的情况,那么不遵循一般规则也没关系。 (但这种情况应该很少见。)
I agree with 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.
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.)
#include "impl.cpp"
有合法用途:测试对静态/等变量的访问
临时模板,例如这些 if c++ 模板机制被证明是不够的(罕见)
#define MACRO (...)
#include "impl.cpp" //
请注意,
#include "impl.cpp"
可能不安全,因为同一文件包含在单独的编译单元中稍后将它们链接在一起。There are legitimate uses for
#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
Note that
#include "impl.cpp"
can be unsafe it same file is included in separate compilation units that are later linked together.我以前用过它,没有任何问题,但我不能保证它是安全的。有时这是我唯一的选择,所以我使用它,否则我将使用 .h 文件。
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.