您如何在#ifdef中执行宏扩展? [英] How do you perform macro expansion within #ifdef?

查看:106
本文介绍了您如何在#ifdef中执行宏扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些相当通用的代码,它们使用预处理器宏在其他宏上添加特定的前缀.这是发生的事情的简化示例:

I have some fairly generic code which uses preprocessor macros to add a certain prefix onto other macros. This is a much simplified example of what happens:

#define MY_VAR(x) prefix_##x

"prefix_"实际上是在其他地方定义的,因此每次包含文件时都会有所不同.它运行良好,但是现在我有一些代码可以在其中一个标记不存在的情况下跳过,但这不起作用:

"prefix_" is actually defined elsewhere, so it will be different each time the file is included. It works well, but now I have some code I would like to skip if one of the tokens doesn't exist, but this doesn't work:

#if defined MY_VAR(hello)

我希望它扩展为:

#ifdef prefix_hello

但是我不知道怎么做.我需要使用MY_VAR()宏进行扩展,因此我不能仅对名称进行硬编码. (实际上是针对某些测试代码,同一代码每次都包含一个不同的前缀以测试一堆类,而我想跳过几个类的几个测试.)

But I can't figure out how. I need to use the MY_VAR() macro to do the expansion, so I can't just hardcode the name. (It's actually for some testing code, the same code gets included with a different prefix each time to test a bunch of classes, and I want to skip a couple of tests for a handful of the classes.)

使用C ++预处理器可以做到这一点吗?

Is this possible with the C++ preprocessor?

更新:

以下是一些可半编译的代码,以进一步说明该问题:(以避免将其压入下面的注释中)

Here is some semi-compilable code to demonstrate the problem further: (to avoid squishing it into the comments below)

#define PREFIX hello

#define DO_COMBINE(p, x)  p ## _ ## x
#define COMBINE(p, x)     DO_COMBINE(p, x)
#define MY_VAR(x)         COMBINE(PREFIX, x)

// MY_VAR(test) should evaluate to hello_test

#define hello_test "blah blah"

// This doesn't work
#ifdef MY_VAR(test)
  printf("%s\n", MY_VAR(test));
#endif

推荐答案

您的程序中是否存在比此问题描述更多的内容?指令

Is there more to your program than this question describes? The directive

#define MY_VAR(x) prefix_##x

恰好定义一个预处理器标识符.通话

defines exactly one preprocessor identifier. The call

blah ^&* blah MY_VAR(hello) bleh <>? bleh

简单地进入预处理器的一端,而没有定义任何内容就从另一端出来.

simply goes in one end of the preprocessor and comes out the other without defining anything.

在没有发生其他魔术的情况下,您不能指望预处理器记住在前面的源代码过程中哪些参数已传递到哪些宏中.

Without some other magic happening, you can't expect the preprocessor to remember what arguments have been passed into what macros over the course of the preceding source code.

您可以做类似的事情

#define prefix_test 1
#if MY_VAR(test) == 1
#undef prefix_test // optional, "be clean"
...
#endif
#undef prefix_test

查询前缀当前是否具有特定值prefix_. (未定义的标识符将替换为零.)

to query whether the prefix currently has the particular value prefix_. (Undefined identifiers are replaced with zero.)

这篇关于您如何在#ifdef中执行宏扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆