将宏标记为已弃用的最佳方法是什么?

时间:2019-08-13 13:06:53

标签: c

我知道如何通过使用标记枚举/函数为不推荐使用 __attribute__ ((deprecated))。但是我怎么标记常量宏 被弃用?

#define MACRO1 4 //This is deprecated macro

1 个答案:

答案 0 :(得分:4)

GCC(可能还有其他)

__attribute__((deprecated))

对于仅带有常量表达式的特定示例,可以使用以下代码:

更改

#define X (4)

#define X_old (4)

然后添加

const int dep __attribute__((deprecated)) = 0;
#define X ((void)dep, X_old)

添加也可以:

#define X (X_old + dep)

对于过程宏,您可以执行以下操作:

#define P_old do { ... } while(0)
#define P do { (void)dep; P_old; } while(0)

(void)的唯一功能是禁止显示警告。谢谢凯文。

#pragma message

另一种解决方案是将所有不赞成使用的宏放在单独的头文件中,并使用pragma。您可以将其与#ifdef结合使用,例如:

#pragma message ("This header contains deprecated macros")

所有编译器

未引用标签

使用未引用的标签:

#define P_old do { ... } while(0)
#define P do { P_IS_DEPRECATED: P_old; } while(0)

这不适用于常量表达式宏,并且要求您使用-Wall进行编译才能获得警告。如果多次使用,将触发错误。

未使用的变量:

#define P_old do { ... } while(0)
#define P do { int P_IS_DEPRECATED; P_old; } while(0)

也不适用于常量表达式。还需要-Wall,但可以多次使用。

侧注

请记住将常量表达式宏封装在括号中。宏#define X 2+3将使2*X之类的表达式扩展为2*2+3而不是2*(2+3)