本文介绍了如何与C preprocessor两次连接起来,扩大宏如在QUOT;阿根廷## _ ## MACRO"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个程序,其中的某些功能的名称是依赖于一定的宏观变量,像这样的宏值:

 #定义变量3
的#define NAME(有趣)有趣的## _ ##变INT NAME(some_function)(int类型的);

不幸的是,宏 NAME()变成了成

  INT some_function_VARIABLE(int类型的);

而不是

  INT some_function_3(int类型的);

所以这显然是错误的方式去了解它。幸运的是,不同的可能值的变量数量很小,所以我可以简单地做一个#如果变量==ñ并单独列出所有的情况下,但我不知道是否有是一个聪明的办法做到这一点。


解决方案

  $猫xx.c
#定义变量3
帕斯特的#define(X,Y)×## _ ##ÿ
#定义EVALUATOR(X,Y)帕斯特(X,Y)
的#define NAME(FUN)EVALUATOR(好玩,可变)EXTERN无效NAME(矿)(字符* X);
$ gcc的-E xx.c
#1xx.c
#1<内置>中
#1<命令行>中
#1xx.cEXTERN无效mine_3(字符* X);
$


<一个href=\"http://stackoverflow.com/questions/1489932/c-$p$pprocessor-and-token-concatenation/1489985#comment1342105_1489971\">asked为什么这需要间接两个层次。该轻率的回答是,因为这是标准如何规定它的工作;你会发现你需要用字符串化运营,相当于招了。

C99的标准包括宏替换,并6.10.3.1盖的说法取代第6.10.3。

In the invocation NAME(mine), the argument is 'mine'; it is fully expanded to 'mine'; it is then substituted into the replacement string:

EVALUATOR(mine, VARIABLE)

Now the macro EVALUATOR is discovered, and the arguments are isolated as 'mine' and 'VARIABLE'; the latter is then fully expanded to '3', and substituted into the replacement string:

PASTER(mine, 3)

The operation of this is covered by other rules (6.10.3.3 'The ## operator'):

So, the replacement list contains x followed by ## and also ## followed by y; so we have:

mine ## _ ## 3

and eliminating the ## tokens and concatenating the tokens on either side combines 'mine' with '_' and '3' to yield:

mine_3

This is the desired result.


If we look at the original question, the code was (adapted to use 'mine' instead of 'some_function'):

#define VARIABLE 3
#define NAME(fun) fun ## _ ## VARIABLE

NAME(mine)

The argument to NAME is clearly 'mine' and that is fully expanded.
Following the rules of 6.10.3.3, we find:

mine ## _ ## VARIABLE

which, when the ## operators are eliminated, maps to:

mine_VARIABLE

exactly as reported in the question.

这篇关于如何与C preprocessor两次连接起来,扩大宏如在QUOT;阿根廷## _ ## MACRO&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:54