【问题标题】:How to determine macro value at compilation time in C?如何在 C 编译时确定宏值?
【发布时间】:2015-07-28 04:06:52
【问题描述】:

如果我的 C 中有一个宏:

#ifdef SIGDET
#if SIGDET == 1
    isSignal = 1;       /*Termination detected by signals*/
#endif
#endif

如何在编译时设置值?它是编译器的一些参数吗?

【问题讨论】:

  • 它实际上还有其他值吗?

标签: c compilation macros cc


【解决方案1】:

C 编译器允许在命令行上定义宏,通常使用-D 命令行选项:

这将宏 SIGDET 定义为值 1

gcc -DSIGDET myprogram.c

你可以这样指定值:

gcc -DSIGDET=42 myprogram.c

您甚至可以将宏定义为空:

gcc -DSIGDET=  myprogram.c

鉴于您的程序是如何编写的,将 SIGDET 定义为空会导致编译错误。将SIGDET 定义为2 与完全不定义SIGDET 具有相同的效果,这可能不是您所期望的。

最好考虑SIGDET 的任何不同于0 的数字定义来触发条件代码。然后你可以使用这些测试:

#ifdef SIGDET
#if SIGDET+0
    isSignal = 1;       /*Termination detected by signals*/
#endif
#endif

或者这个替代方案:

#if defined(SIGDET) && SIGDET+0
    isSignal = 1;       /*Termination detected by signals*/
#endif

【讨论】:

    猜你喜欢
    • 2017-06-03
    • 2011-10-14
    • 1970-01-01
    • 2019-12-30
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    相关资源
    最近更新 更多