预处理程序宏值到Objective-C字符串文字 [英] Preprocessor macro value to Objective-C string literal

查看:70
本文介绍了预处理程序宏值到Objective-C字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在构建设置中定义了预处理器宏

I have a preprocessor macro defined in build settings

FOO=BAR

我想把这个值转换为可以传递给方法的Objective-C字符串文字.以下#define不起作用,但应演示我正在尝试实现的目标:

That value I want to massage into an Objective-C string literal that can be passed to a method. The following #define does not work, but it should demonstrate what I am trying to achieve:

 #define FOOLITERAL @"FOO" //want FOOLITERAL to have the value of @"BAR"

 myMethodThatTakesAnNSString(FOOLITERAL);

我希望我只是以某种方式缺少明显的东西,但是我似乎找不到合适的预处理器伏都教徒来得到我所需要的东西.

I expect that I am just missing the obvious somehow, but I cannot seem to find the right preprocessor voodoo to get what I need.

推荐答案

使用 stringizing运算符 #从符号中制作一个C字符串.但是,由于预处理程序的怪异,您需要使用两层额外的宏:

Use the stringizing operator # to make a C string out of the symbol. However, due to a quirk of the preprocessor, you need to use two extra layers of macros:

#define FOO BAR
#define STRINGIZE(x) #x
#define STRINGIZE2(x) STRINGIZE(x)
#define FOOLITERAL @ STRINGIZE2(FOO)
// FOOLITERAL now expands to @"BAR" 

需要额外的层的原因是,字符串化运算符只能在宏的参数上使用,而不能在其他标记上使用.其次,如果宏的参数在宏的主体中应用了字符串化运算符,则该参数将 not 扩展为另一个宏.因此,为确保扩展 FOO ,我们包装了另一个宏,以便在扩展 STRINGIZE2 时,它也会扩展 FOO ,因为字符串化运算符不会出现在该宏的主体中.

The reason for the extra layers is that the stringizing operator can only be used on the arguments of the macro, not on other tokens. Secondly, if an argument of a macro has the stringizing operator applied to it in the body of the macro, then that argument is not expanded as another macro. So, to ensure that FOO gets expanded, we wrap in another macro, so that when STRINGIZE2 gets expanded, it also expands FOO because the stringizing operator does not appear in that macro's body.

这篇关于预处理程序宏值到Objective-C字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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