Patrick
Patrick

Reputation: 416

preserve whitespace in preprocessor macro value taken from environment variable

In an Objective-C project I am attempting to take a file path from an environment variable and set it as a location to write generated files. This is used to run test code using xcodebuild in an automated testing environment where the file path is not determined until xcodebuild is called.

In attempt to do this I am entering a preprocessor macro in the Build Settings that references the variable:

BUILDSERVER_WORKSPACE=\@\"$(WORKSPACE)\"

and then setting the value of a string using that macro

NSString *workspaceLocation = BUILDSERVER_WORKSPACE;

in cases where the (string value of) the path for $WORKSPACE does not contain spaces it works fine but in cases where the path has spaces, the macro preprocessor sees the whitespaces as a macro separator and attempts to process them as separate macro definitions.

for example:

$WORKSPACE=/foo/bar/thudblat

will set the value of workspacelocation as @"/foo/bar/thudblat" but

$WORKSPACE="/foo/bar/thud blat"

ends up creating multiple preprocessor definitions:

#define BUILDSERVER_WORKSPACE @"/foo/bar/thud

#define blat"

I have attempted to stringify the path, but since the presence or absence of whitespace only happens when i call xcodebuild to build and then run and so I cannot get that to work.

In the end, what I want is to simply take the path at $WORKSPACE and set its value to the NSString *workspaceLocation

so that workspaceLocation could potentially be "\foo\bar\thud blat"

Upvotes: 2

Views: 550

Answers (3)

CRD
CRD

Reputation: 53000

If you wish to really read the environment variable at runtime then you can simply obtain it from NSProcessInfo:

NSString *workspaceLocation = NSProcessInfo.processInfo.environment[@"WORKSPACE"];

That will give you the current value of the environment variables, spaces and all.

HTH

Upvotes: 0

Patrick
Patrick

Reputation: 416

I thought I had tried every scheme of quoting and escaping but, the one thing I had not tried was quoting the entire thing as suggested by @nielsbot BUILDSERVER_WORKSPACE="\@\"$(WORKSPACE)\""

with an unescaped quote at the beginning and end of the entire value statement. Thad did the trick and gave me the string: @"/foo/bar/thud blat" when calling xcodebuild.

Upvotes: 1

pronebird
pronebird

Reputation: 12240

You can achieve that with double stringize trick:

#define STRINGIZE_NX(A) #A
#define STRINGIZE(A) STRINGIZE_NX(A)

static NSString *kWorkspace = @( STRINGIZE(BUILDSERVER_WORKSPACE) );

The way it works is very well explained in here: https://stackoverflow.com/a/2751891/351305

Upvotes: 0

Related Questions