【问题标题】:Should I avoid using guard macros?我应该避免使用守卫宏吗?
【发布时间】:2021-06-03 15:53:28
【问题描述】:

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

#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

/* +++ 文件resolve.c +++ */

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

/* +++ 文件resolve.h +++ */

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

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

我在看什么?

【问题讨论】:

  • 感谢 dbush 在我将代码输入堆栈溢出时看到我的错字,我已更正。我的问题仍然存在,似乎没有必要包含保护宏,甚至更希望在实际上不希望在同一个源文件中多次包含同一个头文件的情况下导致预处理器生成错误。
  • 我故意让这个例子尽可能简单,希望能说明我所指的内容。我正在开发一个有很多源文件的系统。大多数标题都没有嵌套,只能包含一次。还要感谢 user3386109

标签: c macros include preprocessor guard


【解决方案1】:

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

你可以编码

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

【讨论】:

    【解决方案2】:

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

    函数的声明如下所示:

    int pb2au(int mass1, int heat); 
    
    int resolve ( int ir1, int ir2 );
    

    通过此更改,您的代码将编译,并且如果包含多次标头,您将不会遇到问题。不过,无论如何添加标头保护都是一个好主意。

    【讨论】:

      猜你喜欢
      • 2012-10-14
      • 1970-01-01
      • 2010-09-23
      • 2018-06-16
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      相关资源
      最近更新 更多