如果 header 已经隐含地包含在文件中,是否应该将 header 包含在文件中?

Should a header be included in a file if that header is already implicitly included?

我想知道:如果 header 已经被隐式包含在文件中,是否应该包含一个 header? 例如

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 header.

无法编译

一个 real-life 示例是是否包含 <stdlib.h> 以使用 NULL 指针,如果它很可能被隐含地包含在其他一些 header 文件中并且代码在没有额外包含的情况下编译。

这些示例是否说明了 re-include 已隐式包含文件的原因?

如果满足某些条件,您可以根据需要多次包含头文件:

  1. .h 文件受定义保护(您的代码缺少保护)。它确保.h文件的主体在每个编译单元中只编译一次。
#ifndef DATASTRUCTURE_h
#define DATASTRUCTURE_h

/* the content of the .h file */

#endif
  1. 除静态内联函数外,您的代码不包含任何数据或函数定义。它可以包含 extern 个对象声明和函数原型以及数据类型声明。

好不好?我个人更喜欢看哪个特定的编译单元将使用接受与多重预处理相关的惩罚。