How to make a macro that can take a string? How to make a macro that can take a string? objective-c objective-c

How to make a macro that can take a string?


You'll want to use the preprocessor's 'stringizing' operator, #, and probably the 'token pasting' operator, '##':

#define STRINGIFY2( x) #x#define STRINGIFY(x) STRINGIFY2(x)#define PASTE2( a, b) a##b#define PASTE( a, b) PASTE2( a, b)#define PRINTTHIS(text) \    NSLog(PASTE( @, STRINGIFY(text)));

I'm not sure if Objective-C requires the '@' to have no whitespace between it and the opening quote - if whitespace is permitted, drop the PASTE() operation.

Note that you'll need the goofy 2 levels of indirection for STRINGIFY() and PASTE() to work properly with macro parameters. And it pretty much never hurts unless you're doing something very unusual (where you don't want macro parameters expanded), so it's pretty standard to use these operators in that fashion.


Here's one way to write a macro that sticks its argument textually into a string object, though it strikes me as a bit gnarly:

#define PRINTTHIS(text) NSLog((NSString *)CFSTR(#text))

It uses the stringizing operator to turn the argument into a C string, which it then uses to create a CFString, which is toll-free bridged with NSString.


It seems like this would work as well.

#define PRINTTHIS(text) NSLog(@#text);

Just tested it, and it seems to work just fine.