3

I want to create several variables of the form:

static char fooObjectKey;
static char bazObjectKey;
static char wthObjectKey;
static char myObjectObjectKey;
...

So I wrote

#define defineVar(x) static char #x ObjectKey

defineVar(foo);
defineVar(baz);
defineVar(wth);
defineVar(myObject);

but I get the error: Expected identifier or }

What am I doing wrong here? :) Any help is appreciated

4
  • 2
    Most compilers can show you the result of the pre-processor. This is invaluable when trying to fully understand complex macros. Commented Dec 26, 2012 at 10:22
  • I am using LLVM in Xcode, Do you know how can I see the result? :) Commented Dec 26, 2012 at 10:28
  • 1
    @nacho4d with gcc is gcc -E source.c I think that with clang it's the same since clang offers a gcc-compatible driver so clang -E source.c. Commented Dec 26, 2012 at 10:35
  • Found how to do it in Xcode! stackoverflow.com/questions/5937031/xcode-4-preprocessor-output See @Steven Hepting's answer Commented Dec 26, 2012 at 10:47

4 Answers 4

7

You need to concatenate them:

#define defineVar(x) static char x##ObjectKey

Explanation:

The preprocessor operator ## provides a way to concatenate actual arguments during macro expansion. If a parameter in the replacement text is adjacent to a ##, the parameter is replaced by the actual argument, the ## and surrounding white space are removed, and the result is re-scanned. For example, the macro paste concatenates its two arguments:

#define paste(front, back) front ## back

so paste(name, 1) creates the token name1.

Sign up to request clarification or add additional context in comments.

Comments

3

# in macro is used to stringify argument, ## is used for concatenation in macro... in your case, following is the correct syntax..

#define defineVar(arg) static char arg##ObjectKey

if you use this,

#define defineVar(x) static char #x ObjectKey

variable declaration become...

static char "foo" ObjectKey;

Comments

1

Use double hash for concatenation

#define defineVar(x) static char x##ObjectKey

Comments

0
The ## operator concatenates two tokens into one token
Hence 
defineVar(foo) will be replace with static char fooObjectKey

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.