简体   繁体   English

如何调用宏内的宏?

[英]How to call a macro inside a macro?

is it possible to call macro inside a macro in this way: 是否可以通过这种方式在宏内调用宏:

#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));
}

this code returns the followinf error in the compilation: 此代码返回编译中的followinf错误:

test_macro.c: In function 'main': test_macro.c:在函数'main'中:
test_macro.c:9:18: erreur: macro « BB » requiert 5 arguments, mais seulement 2 ont été passés test_macro.c:9:18:erreur:宏“BB”请求5个论点,mais seulement 2ontétépassés
test_macro.c:9:4: erreur: 'BB' undeclared (first use in this function) test_macro.c:9:4:erreur:'BB'未声明(首次使用此功能)
test_macro.c:9:4: note: each undeclared identifier is reported only once for each function it appears in test_macro.c:9:4:注意:每个未声明的标识符仅针对它出现的每个函数报告一次

What you probably want is to supply additional arguments of BB by expansion of AA(n,k) . 您可能想要的是通过扩展AA(n,k)来提供BB的其他参数。 As pointed by Sourav Ghosh, in your program, AA(n,k) is expanded after being passed to BB as a single argument. 正如Sourav Ghosh指出的那样,在你的程序中, AA(n,k)在作为单个参数传递给BB之后被扩展。 To get it expanded before, you can use one more macro level and define your program as: 要在之前扩展它,您可以再使用一个宏级别并将您的程序定义为:

#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));
}

In your code, when the following line is encountered, in preprocessing stage, 在您的代码中,遇到以下行时,在预处理阶段,

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

as per the rule of MACRO substitution, first, BB will get expanded (replaced) as specified in the replacement-list , then, in the replacement list, if any other MACRO substitution is possible (here, AA ), that will take place next. 根据MACRO替换的规则,首先, BB将按照替换列表中的指定进行扩展(替换),然后,在替换列表中,如果可以进行任何其他MACRO替换(此处为AA ),则接下来将进行。

There the problem arises. 出现了问题。 MACRO definition of BB takes 5 arguments, but you're passing only 2, because, the expansion of AA did not take place yet. 的宏定义BB需要5个参数,但你只有2正在传递,因为,扩大AA未能成行呢。

Related, from C11 , chapter §6.10.3, Macro replacement ( emphasis mine ) 相关的,从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. 然后重新扫描替换列表以获取更多宏名称,如下所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM