包括头文件与实现文件(C ++) [英] including files in header vs implementation file (C++)
问题描述
您好,我只有一个简短的问题。
这
例如:
// test.h
#includeglobals.h
class Test
{
Test();
};
vs
// test.cpp
#includeglobals.h
Test :: Test()
{
}
一般原则是你希望尽可能减少依赖, / p>
-
如果您的接口(.h)引用了给定标题中的任何内容, #include in the interface(.h)
-
如果您只引用不在您的界面中),那么您应该只在实现中包含该标头
-
所以对于上面的例子,如果你不引用任何东西从globals.h在test.h,但你引用它在test.cpp,然后#include应该在test.cpp。如果你在test.h中引用globals.h中的任何内容,那么你需要在test.h中加入#include。
Hi I just have a quick question. What's the difference between including a header file in a header file vs including it in a implementation file?
This
Ex:
// test.h
#include"globals.h"
class Test
{
Test();
};
vs
//test.cpp
#include"globals.h"
Test::Test()
{
}
The general principle is that you want to minimise dependencies wherever reasonably possible, so:
if your interface (.h) references anything in a given header then that header needs to be #included in the interface (.h)
if you only reference a given header in your implementation (.cpp) (and not in your interface) then you should only #include that header in the implementation
you should also try to only #include headers that are actually needed, although this can be difficult to maintain during the lifetime a large project
So for your example above, if you don't reference anything from globals.h in test.h, but you do reference it in test.cpp, then the #include should go in test.cpp. If you reference anything from globals.h in test.h though then you need the #include in test.h.
这篇关于包括头文件与实现文件(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!