我应该避免使用保护宏吗?

时间:2021-03-04 23:26:04

标签: c macros include preprocessor guard

我很清楚经常提到的关于使用守卫宏的原因

#ifndef special_func_lib
#define special_func_lib
...
#endif

我理解允许多个包含很重要 由于“嵌套”,特别是在单个源文件中创建库实用函数集时。

为高级函数集创建头文件时(即不希望包含在另一个包含中)我希望如果包含相同的头文件,预处理器会产生错误不止一次,而不仅仅是忽略它。

例如:

/* +++++++ 文件 main.c +++++ */

#include main.h
int main () {
int pb2au1= resolve( POTION, 1);
int pb2au2= resolve( POTION, 2);
exit pb2au1 + pbau2;
}

/* +++ 文件 main.h +++ */

#include <stdio.h>
int pb2au(int mass1, int heat); /* protype */
#define POTION 886688

/* +++ 文件解析.c +++ */

#include resolve.h
int resolve ( int mass, int heat )
{ return  mass + heat }

/* +++ 文件解析.h +++ */

int resolve ( int ir1, int ir2 ); /* protype */

我不希望在单个源文件中多次包含 main.h 或 resolve.h。

我在看什么?

2 个答案:

答案 0 :(得分:2)

<块引用>

为高级函数集创建头文件时(即不希望包含在另一个包含中)我希望预处理器产生错误

你可以编码

/*in file header.h*/
#ifdef HEADER_H_INCLUDED
#error header.h already included
#endif
#define HEADER_H_INCLUDED
/// other declarations should go here

答案 1 :(得分:1)

您在头文件中拥有的不是函数的声明,而是定义。这些定义与 .c 文件中的定义冲突。

函数的声明如下所示:

int pb2au(int mass1, int heat); 

int resolve ( int ir1, int ir2 );

通过此更改,您的代码将被编译,并且如果头文件被多次包含,您将不会出现问题。尽管如此,无论如何添加标题保护是个好主意。

相关问题