I've defined a few macros that make it simpler to define an array of structures, but I can't find a way to use them without generating errors. Here are the macros (and a few example structures to demonstrate why the macros might be used (the actual structures I'm populating are a little more complex)):
struct string_holder {
const char *string;
};
struct string_array_holder {
struct string_holder *holders;
};
#define DEFINE_STRING_ARRAY_HOLDER(name, values) \
static struct string_holder name##__array[] = values; \
static struct string_array_holder name = { name##__array }
#define WRAP_STRING(string) { string }
It works just fine when you use it to declare an array with one item:
DEFINE_STRING_ARRAY_HOLDER(my_string_array_holder, {
WRAP_STRING("my string")
});
But when I use multiple items:
DEFINE_STRING_ARRAY_HOLDER(my_string_array_holder, {
WRAP_STRING("hello"),
WRAP_STRING("world")
});
I get this error:
error: too many arguments provided to function-like macro invocation
So it's interpreting the comma in the braces as an argument separator. I follow the advice from this question and put parentheses around the problematic argument:
DEFINE_STRING_ARRAY_HOLDER(my_string_array_holder, ({
WRAP_STRING("hello"),
WRAP_STRING("world")
}));
Now when I try to compile it, it interprets ({ ... })
as a statement expression and complains:
warning: use of GNU statement expression extension
(a bunch of syntax errors resulting from its interpretation as a statement expression)
error: statement expression not allowed at file scope
How can I either:
- Use the macro without errors (preferred), or
- Rewrite the macro[s] to work in these circumstances?