假设我的代码如下所示:
#ifdef COND1
extern int func1(void);
#endif
...
#ifdef CONDN
extern int funcn(void);
#endif
my_struct funcs[] = {
#ifdef COND1
{"func1 description", func1},
#endif
...
#ifdef CONDN
{"funcn description", funcn},
#endif
{NULL, NULL},
};
是否可以将其替换为 X macros为了尽量减少两部分函数名称和条件的重复?
如果没有 #ifdef CONDX
条件,这似乎很简单。但是,我不知道如何将它们包含在 X 宏中,因为不允许在 #define
中使用 #ifdef
。
最佳答案
不确定 X 宏 是否是这里的解决方案。但是,您可以使用一些预处理器魔法来减少输入。问题仍然是您示例中的条件编译 (#ifdef
s)。如果不知道这些条件是什么样的,就很难进一步减少输入量。
考虑以下几点:
#define D(n) extern int func ## n(void);
#define A(n) {"func" #n " description", func ## n},
#ifdef COND1
D(1)
#endif
#ifdef COND2
D(2)
#endif
my_struct funcs[] = {
#ifdef COND1
A(1)
#endif
#ifdef COND2
A(2)
#endif
};
我认为,这是朝着您的目标方向迈出的一步。要查看它的作用,您可以尝试
gcc -E -DCOND1 <file-with-contents-above>.c
(如果你在某些 Unix 上)或者
cl -E -DCOND1 <file-with-contents-above>.c
(如果您在 Windows 上使用 Visual Studio)。
关于c - 将 C X 宏与 #ifdef 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30642120/