【发布时间】:2021-01-25 10:57:13
【问题描述】:
我想知道:如果文件头已经隐式包含,是否应该在文件中包含该头文件?例如
dataStructure.h
#ifndef DATASTRUCTURE_H
#define DATASTRUCTURE_H
typedef struct MyStruct_ {
int number;
... // other members
} MyStruct;
#endif
utils.h
#ifndef UTILS_H
#define UTILS_H
#include "dataStructure.h"
int GetSize(MyStruct* my_struct);
int PrimeNumber(int my_struct_number);
#endif
main.c
#include "utils.h"
// utils.h includes `dataStructure.h` but should I include it again here?
int main() {
MyStruct my_struct;
... // initialise my_struct
if (PrimeNumber(my_struct.number)) {
printf("%d is prime\n", my_struct.number);
}
}
如果稍后在utils.h文件中删除GetSize方法,utils.h不再需要包含dataStructure.h。然后在这些修改之后突然main.c没有dataStructure.h标头就无法编译。
一个真实的例子是是否包含 <stdlib.h> 以使用 NULL 指针,如果这很可能会被隐式包含在其他一些头文件中,并且代码在没有额外包含的情况下编译。
如果文件已被隐式包含,这些示例是否说明了重新包含文件的理由?
【问题讨论】:
-
我的意见是,你应该在你使用它的地方包括你使用的东西。