我在处理的程序中遇到问题。我正在尝试 --help 来显示编译了哪些功能。但是,其中有很多,“正常”方式太冗长了。例如:
#ifdef HAVE_FOO
static const bool have_foo = true;
#else
static const bool have_foo = false;
#endif
printf("Support for foo: %s\n", have_foo ? "yes" : "no");
现在,由于我基本上必须为每个功能执行此操作,所以会有很多行,这是我不想要的。
所以我想我应该为它写一些宏:
#define _SUPP(X) #ifdef HAVE_##X \
static const bool _##X##_SUPP = true; \
#else \
static const bool _##X##_SUPP = false; \
#endif
#define _PRINTSUPP(var, name, desc) printf("\t%s - %s: %s\n", name, desc, _##var##_SUPP ? "yes" : "no")
但是,这里有一个问题。宏将扩展为一行,预处理器会因此而阻塞。有没有办法生成一个中间有实际换行符的宏,或者是否可以在单行上评估 #ifdef
?
最佳答案
如果不是不定义 HAVE_FOO
,而是将其定义为 0
,您可以:
const struct {
bool present;
const char *name;
} features[NFEATURES] = {
{HAVE_FOO, "foo"},
{HAVE_BAR, "bar"},
...
};
for (size_t i=0; i < NFEATURES; i++)
if (features[i].present)
printf(" ... and we've got: %s\n", features[i].name);
您必须检查 #if HAVE_FOO
而不是 #ifdef HAVE_FOO
然后,您的 --help
消息可能会显示如果您的功能数量达到数以亿计,速度会慢一点(在这种情况下,无论如何我都会推荐不同的架构)。
关于c - 使用另一个宏生成#ifdef、#endif 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4792825/