c++ - 在 .cpp 或 .h 中包含头文件的最佳方法是什么?

标签 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的第一个文件。如果有任何编译器错误,则意味着 myMath.h 不能自给自足。

myMath.cpp:

#include "myMath.h"

// Rest of the file.

另一个指导原则是 .h 文件不得#include 任何其他头文件,除非它需要其中的某些内容。您可以从头文件中删除 #include 行,只要删除它们不会违反自给自足准则即可。

关于c++ - 在 .cpp 或 .h 中包含头文件的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40123185/

相关文章:

c++ - #include <mutex> 导致 bind() 函数调用在编译时抛出错误,为什么?

c++ - 减少for循环的时间

python - SWIG:如何将 python 文件合并到 swig 生成的最终模块文件中

c++ - 当 2 个线程共享同一个物理内核时,具有错误共享的 volatile 增量在发布时比在调试时运行得更慢

c++ - 如何分配 "array of object"的指针 (C++)

c++ - Crypto++ 是否支持 TOFB-I?

c++ - 使用 &front() 修改 std::string 中的底层字符数组

c++ - 如何在 Cocos2dx-v3 C++ 中将 Map<K, V> 与 string 和 int 一起使用?

c++ - const std::string 具有内部链接,但似乎不适用于 const std::string&

c++ - 使用指向 igzstreams 的指针的 STL vector 读取 gzip 文件