nacho4d
nacho4d

Reputation: 45158

Macro for creating variables in C

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

Upvotes: 3

Views: 290

Answers (4)

MByD
MByD

Reputation: 137442

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.

Upvotes: 7

Gaurav
Gaurav

Reputation: 221

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

Upvotes: 0

Adeel Ahmed
Adeel Ahmed

Reputation: 1601

# 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;

Upvotes: 3

milleniumbug
milleniumbug

Reputation: 15834

Use double hash for concatenation

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

Upvotes: 1

Related Questions