哪种方式最好,包括.cpp或.h中的头文件?

时间:2016-10-19 05:49:18

标签: c++

myMath.h

#include <stdio.h>
#include <math.h>
  add... something
  add... something


or

myMath.cpp

#include <stdio.h>
#include <math.h>
  add... something
  add... something

哪种方式最好包含头文件?

我知道它更好,因为.h具有最小值,因为#include只是复制和过去

2 个答案:

答案 0 :(得分:4)

指导原则是每个.h文件必须是自给自足的 - 它应该是可编译的,不需要任何代码行。

测试myMath.h是否自给自足的最佳方法是将它作为myMath.cpp中的第一个文件#include d。如果有任何编译器错误,则意味着myMath.h不够自给。

myMath.cpp:

#include "myMath.h"

// Rest of the file.

另一个指导原则是.h文件不能#include任何其他头文件,除非它需要来自它们的东西。您可以从头文件中删除#include行,只要删除它们不会破坏自给自足的准则。

答案 1 :(得分:1)

由于头文件可能包含多个源(.cpp)文件,因此通常最好将标头中的包含限制为最小。通过这种方式,您可以避免包括太多&#34;在源文件中。

为了进一步减少这种情况,您经常转发仅通过引用或指针使用的声明类,例如:

// file.h
class Object;                          // note: no header included, clients will need to include themselves
Object* createRawObject();

// file.cpp
#include <Object.h>                    // note: header included, Object defined
Object* createRawObject() { return new Object(42); }