vagrant vagrant - 1 year ago 156
Objective-C Question

Preprocessor macro value to Objective-C string literal

I have a preprocessor macro defined in build settings


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"


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.

Answer Source

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
// FOOLITERAL now expands to @"BAR" 

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download