【问题标题】:Should a header be included in a file if that header is already implicitly included? [closed]如果该标头已被隐式包含,是否应将标头包含在文件中? [关闭]
【发布时间】: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 指针,如果这很可能会被隐式包含在其他一些头文件中,并且代码在没有额外包含的情况下编译。

如果文件已被隐式包含,这些示例是否说明了重新包含文件的理由?

【问题讨论】:

  • 我的意见是,你应该在你使用它的地方包括你使用的东西。

标签: c gcc header include


【解决方案1】:

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

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

/* the content of the .h file */

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

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

【讨论】:

    猜你喜欢
    • 2012-12-08
    • 1970-01-01
    • 2011-05-14
    • 2011-10-05
    • 2019-05-15
    • 2013-07-17
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多