c - 如何在 C 语言的#define 宏中用字符串常量替换函数名

标签 c string macros c-preprocessor preprocessor-directive

我希望使用预处理器指令将函数调用替换为字符串。 像这样:

#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/

相关文章:

macros - 如何在模块中定义和使用宏?

c - 尝试读取 json 文件时出现段错误

c - c/c++ 中的 3D 或 2D 图形?

c - 旋转的弦

java - 如何在 JAVA 中将字符串转换为整数数组并返回

mysql - 在 ComboBox.Item 中隐藏部分 String.Format

c - 如何在 C 中共享具有共享内存的两个不相关进程之间的指针结构?

cvCreateVideoWriter - 无法在后续调用中更改文件名

sql - 如何防止宏产生的自动链接方括号的汇合?

iphone - ifdef语法不起作用