如何在宏中调用宏?

How to call a macro inside a macro?

是否可以这样在宏内部调用宏:

#include <stdio.h>
#define AA(a1, a2) a1, 3, 5, a2
#define BB(x, y1, y2, y3, y4) { printf("%d %d %d %d %d\n",x, y1, y2, y3, y4 ); }

int main ()
{
   int n = 21, k= 11;
   BB(31, AA(n,k));
}

此代码returns编译时出现以下错误:

test_macro.c: In function ‘main’:
test_macro.c:9:18: erreur: macro « BB » requiert 5 arguments, mais seulement 2 ont été passés
test_macro.c:9:4: erreur: ‘BB’ undeclared (first use in this function)
test_macro.c:9:4: note: each undeclared identifier is reported only once for each function it appears in

在你的代码中,当遇到下面一行时,在预处理阶段,

BB(31, AA(n,k));

根据 MA​​CRO 替换规则,首先,BB 将按照 替换列表 中的指定进行扩展(替换),然后,在替换列表中, 如果任何其他宏替换是可能的(这里,AA),接下来将发生。

问题就出现了。 BB 的 MACRO 定义有 5 个参数,但你只传递了 2 个,因为 AA 的扩展还没有发生。

相关,来自C11,章节§6.10.3,宏替换(强调我的

A preprocessing directive of the form

  # define identifier replacement-list new-line

defines an object-like macro that causes each subsequent instance of the macro name to be replaced by the replacement list of preprocessing tokens that constitute the remainder of the directive. The replacement list is then rescanned for more macro names as specified below.

您可能想要通过扩展 AA(n,k) 来提供 BB 的附加参数。正如 Sourav Ghosh 所指出的,在您的程序中, AA(n,k) 在作为单个参数传递给 BB 后被扩展。要在之前扩展它,您可以使用更多的宏级别并将您的程序定义为:

#define AA(a1, a2) a1, 3, 5, a2
#define BB(x, y1, y2, y3, y4) { printf("%d %d %d %d %d\n",x, y1, y2, y3, y4 ); }
#define BBB(a,b) BB(a,b)

int main ()
{
  int n = 21, k= 11;
  BBB(31, AA(n,k));
}