Jeff Lamb
Jeff Lamb

Reputation: 5865

C macro concatenation to create a struct

I'm trying to create a macro to automate the creation of accessors for different types of variables in a simple "database" in C. This is done via a struct:

typedef struct {
    int var1;
    long var2;
    double var3;
    int var4;
} dataNames_t;

But to automate things, I'd like to create a bunch of macros to mimic overloading of functions so I don't have to have individual getInt, getBool, getLong, etc functions. We do this fairly often so we can very quickly add entries to long lists of very similar things. This way we don't have to modify 5 places in a file to add an entry. However, I can't seem to figure it out for a structure.

#define DATA_LIST        \
  DM(var1, int),         \
  DM(var2, long),        \
  DM(var3, double),      \
  DM(var4, int)

#define DM(y, z)    z y;

/* create data structure from the macro */
typedef struct {
    DATA_LIST
} dataNames_t;

This struct should evaluate to the first one, but something's not working right.

#define DM(y, z)    z y##;

doesn't work, either.

Upvotes: 2

Views: 5483

Answers (4)

jfm3
jfm3

Reputation: 37774

Remove the commas from DATA_LIST:

#define DATA_LIST        \
  DM(var1, int),         \
  DM(var2, long),        \
  DM(var3, double),      \
  DM(var4, int)

Upvotes: 0

Artelius
Artelius

Reputation: 49089

Use the -E flag in gcc if you want to see the output of the preprocessor. This can be very useful in debugging macros.

However in this case, the problem is the commas on each line here:

  DM(var1, int),         \
  DM(var2, long),        \
  DM(var3, double),      \
  DM(var4, int)

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272537

I suspect the problem is the comma after every DM() in your DATA_LIST macro.

Upvotes: 0

Blair Holloway
Blair Holloway

Reputation: 16509

The problem is the comma at the end of each DM(...) in your DATA_LIST; your struct is effectively expanding to:

typedef struct {
    int var1;,
    long var2;,
    double var3;,
    int var4;
} dataNames_t;

Change your DATA_LIST to:

#define DATA_LIST       \
  DM(var1, int)         \
  DM(var2, long)        \
  DM(var3, double)      \
  DM(var4, int)

Upvotes: 5

Related Questions