用另一个宏生成#ifdef、#endif 子句
我正在处理的程序遇到问题。我正在尝试使用 --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
?
I'm having a problem in a program I'm working on. I'm trying in --help to display which features are compiled in or not. However, there are quite alot of these and the "normal" way is too verbose. E.g.:
#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");
Now, since I have to do this basically for every feature, it will be loads of lines, which I do not want.
So I thought I'd write some macros for it:
#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")
However, there is an issue here. The macro will be expanded to a single line, and the preprocessor chokes on this. Is there a way to generate a macro with actual newlines inbetween, or is it possible to evaluate an #ifdef
on a single line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能使用宏来创建另一个预处理指令。所有预处理指令都会在宏扩展开始之前被识别,因此您的宏将被解释为错误的 C 代码。
You cannot use a macro to create another preprocessing directive. All preprocessing directives are recognized before macro expansion begins, so your macro will be interpreted as erroneous C code.
您无法在 C 中执行此操作。通常的方法是从 Perl 或 Python 等语言中的某些文本描述生成这样的标头。
You cannot do this in C. The usual approach is to generate such a header from some textual description in, say, Perl or Python.
如果您不是不定义
HAVE_FOO
,而是将其定义为0
,则可以执行以下操作:您必须检查
#if HAVE_FOO
然后,如果您的功能数量达到无数(在这种情况下,我建议使用无论如何,不同的架构)。If, instead of not defining
HAVE_FOO
, you define it to0
, you can do:You'll have to check for
#if HAVE_FOO
instead of#ifdef HAVE_FOO
then, and your--help
message may be displayed a bit slower if your number of features runs in the zillions (in which case I'd recommend a different architecture anyway).