如何检查C中宏是否已定义且其值为true。

huangapple go评论89阅读模式
英文:

How to check if macro is defined and its value is true in C

问题

我正在处理一个包含多个产品并共享相同代码基础的项目。每个产品都有与之关联的 product_XXX.h 文件,使用 #define 指令来定义宏。我想要为单个产品引入一个新的宏。例如:

#define FANCY_FEATURE 1

换句话说,我不想将其添加到所有其他产品中并将其设置为零。

现在在代码中,为了使其在所有项目中都能编译,我需要检查是否已定义它。我还想检查并确保 FANCY_FEATURE 被设置为 1。如何同时执行这两个步骤呢?

#if defined (FANCY_FEATURE) && (FANCY_FEATURE) 浮现在我的脑海中,但我不确定执行顺序(例如:右边的表达式是否首先被评估),以及是否会在使用不同编译器时生成错误。

英文:

I am working on a project that has multiple products and they all share the same code base. Each product has a product_XXX.h file associated with it that use #define directive to define macros. I would like to introduce a new macro for a single product only.
For example:

#define FANCY_FEATURE 1

In other words, I don't want to add this to all the other products and set it to zero.

Now in the code, in order for it to compile for all the projects, I need to check if it is defined. I also want to check and make sure FANCY_FEATURE is set to 1. How can I do these two steps at once.

#if defined (FANCY_FEATURE) && (FANCY_FEATURE) came to my mind but I wasn't sure about the order of execution (e.g.: right hand side being evaluated first) and if it would generate an error using different compilers.

答案1

得分: 4

只需编写 #if A

简短的演示程序:

#include <stdio.h>

// 尝试所有3个变体:

#define A 1
//#define A 0
//#undef A

int main()
{
#if defined(A) && A
  printf("defined(A) && A\n");
#endif

#if A
    printf("#if A\n");
#endif
}
英文:

Just write #if A.

Short demo program:

#include &lt;stdio.h&gt;

// Try all 3 variants:

#define A 1
//#define A 0
//#undef A

int main()
{
#if defined(A) &amp;&amp; A
  printf(&quot;defined(A) &amp;&amp; A\n&quot;);
#endif

#if A
    printf(&quot;#if A\n&quot;);
#endif
}

huangapple
  • 本文由 发表于 2023年7月7日 00:37:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76630908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定