这是最好的方式,包括头文件在.cpp或.h

  • 本文关键字:文件 cpp 包括头 方式 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只是复制和过去

指导原则是每个。h文件必须是自给自足的——它应该是可编译的,而不需要更多的代码行。

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

myMath.cpp:

#include "myMath.h"
// Rest of the file.

另一个指导原则是,.h文件不能#include任何其他头文件,除非它需要从他们那里得到一些东西。您可以从头文件中删除#include行,只要删除它们不违反自给自足准则。

由于头文件可能被许多源文件(.cpp)包含,因此通常最好将头文件中的包含限制到最小。这样可以避免在源文件中包含"太多"内容。

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

// 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); }

最新更新