Besi
Besi

Reputation: 22939

C macro that creates an NSString variable with the variable name as the content of the string

Despite the fact that this is not good coding practice, I want a macro that should work like the following:

CREATE_STRING(fooBar)

And it should create the following code:

NSString *fooBar = @"fooBar";

My macro looks like this:

#define CREATE_STRING(varName) NSString *varName = @"varName";

But now I get the following

NSString *fooBar = @"varName";

It seems to be such an easy problem to solve and I have already checked the documentation from IBM but I just can't seem to get the varName into the string.

Upvotes: 7

Views: 3482

Answers (2)

user529758
user529758

Reputation:

Use

#define CREATE_STRING(varName) NSString *varName = @#varName

instead. (also note that you don't need the trailing semicolon in order to be able to "call" your macro as a C-like function.)

Upvotes: 15

JeremyP
JeremyP

Reputation: 86651

This is how to do it

#define CREATE_STRING(varName) NSString *varName = @"" #varName

It takes advantage of the fact that two string constants one after the other get concatenated by the compiler.

Upvotes: 10

Related Questions