Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preprocessor macro value to Objective-C string literal

I have a preprocessor macro defined in build settings

FOO=BAR 

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.

like image 233
vagrant Avatar asked Sep 30 '11 04:09

vagrant


People also ask

What does #define do in Objective C?

#define name value , however, is a preprocessor command that replaces all instances of the name with value . For instance, if you #define defTest 5 , all instances of defTest in your code will be replaced with 5 when you compile. Follow this answer to receive notifications.

What is macro in Objective C?

Macros can be used in many languages, it's not a specialty of objective-c language. Macros are preprocessor definitions. What this means is that before your code is compiled, the preprocessor scans your code and, amongst other things, substitutes the definition of your macro wherever it sees the name of your macro.

How do you define a string macro?

We can create two or more than two strings in macro, then simply write them one after another to convert them into a concatenated string. The syntax is like below: #define STR1 "str1" #define STR2 " str2" #define STR3 STR1 STR2 //it will concatenate str1 and str2.


1 Answers

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"  

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.

like image 103
Adam Rosenfield Avatar answered Oct 28 '22 08:10

Adam Rosenfield