gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:29:40 26 4
gpt4 key购买 nike

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 会更好,因为 #include 只是复制和过去

最佳答案

指导原则是每个 .h 文件都必须是自给自足的——它应该是可编译的,无需任何更多代码行。

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

我的数学.cpp:

#include "myMath.h"

// Rest of the file.

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com