英文:
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 <stdio.h>
// Try all 3 variants:
#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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论