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

nacho4d
  • 43,720
  • 45
  • 157
  • 240
  • 2
    Most compilers can show you the result of the pre-processor. This is invaluable when trying to fully understand complex macros. – Eli Iser Dec 26 '12 at 10:22
  • I am using LLVM in Xcode, Do you know how can I see the result? :) – nacho4d Dec 26 '12 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`. – user1797612 Dec 26 '12 at 10:35
  • Found how to do it in Xcode! http://stackoverflow.com/questions/5937031/xcode-4-preprocessor-output See @Steven Hepting's answer – nacho4d Dec 26 '12 at 10:47

4 Answers4

8

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.

MByD
  • 135,866
  • 28
  • 264
  • 277
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;
Adeel Ahmed
  • 1,591
  • 8
  • 10
1

Use double hash for concatenation

#define defineVar(x) static char x##ObjectKey
milleniumbug
  • 15,379
  • 3
  • 47
  • 71
0
The ## operator concatenates two tokens into one token
Hence 
defineVar(foo) will be replace with static char fooObjectKey
Gaurav
  • 221
  • 1
  • 4
  • 8