我可以在中间而不是结尾使用__VA_ARGS定义可变参数C预处理器宏吗?

sal*_*r p 6 c gcc c99 c-preprocessor variadic-macros

如果我这样做,海湾合作委员会会抱怨:

#define M(obj,met, ..., contents) obj##_##met(const void * self, __VA_ARGS__) { \
   contents \
   }
Run Code Online (Sandbox Code Playgroud)

给我这两个理由:

error: missing ')' in macro parameter list
warning: __VA_ARGS__ can only appear in the expansion of a C99 variadic macro
Run Code Online (Sandbox Code Playgroud)

显然,C99样式的可变参数宏在省略号之后立即期望右括号,有效地要求可变参数列表是宏的最后一个参数.我需要它在中间来产生我在上面的宏中描述的速记符号.GCC是否支持此功能,使用另一种(非C99)可变参数宏样式?我可以模仿它在其他地方做吗?我不希望最后的变量列表,它会让我的符号混乱.我只能使用GCC.

ken*_*ytm 9

不,你不能.在...必须出现在年底.

但你可以定义M

#define M(obj,met, ...) obj##_##met(const void * self, __VA_ARGS__)
Run Code Online (Sandbox Code Playgroud)

并用它作为

void M(foo, bar, int x, char y, double z) {
   content;
}
Run Code Online (Sandbox Code Playgroud)


Pau*_* II 6

你必须把它...放在最后,但是使用LASTPOP_LAST宏,你可以为你的宏保持相同的参数顺序,并像这样定义它:

#define M(obj,met, ...) obj##_##met(const void * self, POP_LAST(__VA_ARGS__)) { \
   LAST(__VA_ARGS__) \
   }
Run Code Online (Sandbox Code Playgroud)

下面是如何定义这些宏:

/* This counts the number of args */
#define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1)

/* This will let macros expand before concating them */
#define PRIMITIVE_CAT(x, y) x ## y
#define CAT(x, y) PRIMITIVE_CAT(x, y)

/* This will pop the last argument off */
#define POP_LAST(...) CAT(POP_LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define POP_LAST_1(x1)
#define POP_LAST_2(x1, x2) x1
#define POP_LAST_3(x1, x2, x3) x1, x2
#define POP_LAST_4(x1, x2, x3, x4) x1, x2, x3
#define POP_LAST_5(x1, x2, x3, x4, x5) x1, x2, x3, x4
#define POP_LAST_6(x1, x2, x3, x4, x5, x6) x1, x2, x3, x4, x5
#define POP_LAST_7(x1, x2, x3, x4, x5, x6, x7) x1, x2, x3, x4, x5, x6
#define POP_LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x1, x2, x3, x4, x5, x6, x7

/* This will return the last argument */
#define LAST(...) CAT(LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define LAST_1(x1) x1
#define LAST_2(x1, x2) x2
#define LAST_3(x1, x2, x3) x3
#define LAST_4(x1, x2, x3, x4) x4
#define LAST_5(x1, x2, x3, x4, x5) x5
#define LAST_6(x1, x2, x3, x4, x5, x6) x6
#define LAST_7(x1, x2, x3, x4, x5, x6, x7) x7
#define LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x8
Run Code Online (Sandbox Code Playgroud)

这些宏最多可用于8个参数.如果您愿意,可以轻松扩展它们以处理更多内容.