我希望使用预处理器指令将函数调用替换为字符串。 像这样:
#ifdef DEBUG
#define Func1(arg) "Function not supported"
#endif
所以基本上当有人调用这个函数时,我想要一个编译错误,这样这个函数在 DEBUG
模式下是不可见的,取而代之的是,在编译日志中打印以下字符串。
此方法抛出错误。
当调用 func1()
时,是否有任何其他方法可以打印我想要的特定字符串?
最佳答案
实现此类行为的最明显方法是使用#error
指令。然而,由于不可能构造“条件 #error
指令”,我猜下一步是 C99 中引入的 _Pragma
运算符。这是在编译期间产生消息的解决方案:
#include <stdio.h>
#define DEBUG 1
#ifdef DEBUG
#define Func1(arg) _Pragma("message \"Function not supported.\"")
#endif
void (Func1)(int arg)
{
}
int main(void)
{
Func1(1);
Func1(2);
Func1(3);
return 0;
}
编译(使用gcc
):
...
check.c:15: note: #pragma message: Function not supported.
check.c:16: note: #pragma message: Function not supported.
check.c:17: note: #pragma message: Function not supported.
我知道这不是直接的解决方案(这样的消息甚至不被视为警告,所以 -Werror
不会改变任何东西),但是你可以使用例如grep
工具或任何其他扫描编译器输出的方法。
从 GCC 4.8 开始还有 #pragma GCC error "message"
,这是直接(但不可移植)的解决方案。检查this answer了解更多信息。例如:
#ifdef DEBUG
#define Func1(arg) _Pragma("GCC error \"Function not supported.\"")
#endif
关于c - 如何在 C 语言的#define 宏中用字符串常量替换函数名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24758100/