Can I define variadic C preprocessor macros with __VA_ARGS in the middle instead of the end?

salvador p picture salvador p · Oct 3, 2010 · Viewed 11.8k times · Source

GCC complains if I do this:

#define M(obj,met, ..., contents) obj##_##met(const void * self, __VA_ARGS__) { \
   contents \
   }

Giving me these 2 reasons:

error: missing ')' in macro parameter list
warning: __VA_ARGS__ can only appear in the expansion of a C99 variadic macro

Apparently, C99 - style variadic macros expect the closing parenthesis immediately after the ellipsis, effectively demanding that the variadic list be the last arguments of the macro. I need it to be in the middle to produce my shorthand notation described in the above macro. Does GCC support this feature, using another (non-C99) variadic macro style? Can I emulate it doing it someway else? I don't want the variadic list at the end, it will make my notation confusing. And I can only use GCC.

Answer

kennytm picture kennytm · Oct 3, 2010

No you can't. The ... must appear at the end.

But you could define M as

#define M(obj,met, ...) obj##_##met(const void * self, __VA_ARGS__)

and use it as

void M(foo, bar, int x, char y, double z) {
   content;
}