Stringify Endpoint for Xcode LLVM Processor Macros

2019-09-11 01:01发布

问题:

In the "Apple LLVM 7.0 - Preprocessing" section under the "Build Settings" tab, I've defined a Preprocessor Macros as:

STR(arg)=#arg
HUBNAME=STR("myhub")
HUBLISTENACCESS=STR("Endpoint=sb://abc-xyz.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=JKLMNOP=")

In my code, I'm trying to refer to the value of HUBLISTENACCESS as a string:

SBNotificationHub* hub = [[SBNotificationHub alloc] initWithConnectionString:@HUBLISTENACCESS notificationHubPath:@HUBNAME];

But I'm getting errors from Xcode for the initialization of "hub":

Expected ';' at end of declaration

Unterminated function-like macro invocation

Unexpected '@' in program

I suspect that the definition of HUBLISTENACCESS in the Preprocessor Macros needs to be properly escaped but I've tried a few things and can't seem to get it right. Can somebody help me understand what I'm doing wrong?

回答1:

There's one very obvious reason why you were trying to do failed: you use // in the HUBLISTENACCESS. As in C, things after // were commented out so in the aspect of the compiler, the last line of yours is actually:

HUBLISTENACCESS=STR("Endpoint=sb:

To test it, just remove one slash and it will work again. What you were doing like trying to define things as such:

#define FOO //

which I don't think it's possible. I honestly have no idea how you can do that within the Build Settings, but there are other ways to do it globally via a PCH file (prefix header).

A simple line within the PCH will will save all those troubles:

#define HUBLISTENACCESS @"Endpoint=sb://abc-xyz.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=JKLMNOP="

Then use it as below: (no more @ needed!)

NSLog(@"%@", HUBLISTENACCESS);