问题描述
我要创建一个基于一个名字创建了一个函数是C宏
上的行号。
我以为我可以像做(真正的功能将有括号内的语句):
I want to create a C macro that creates a function with a name basedon the line number.I thought I could do something like (the real function would have statements within the braces):
#define UNIQUE static void Unique_##__LINE__(void) {}
这点我希望这将扩大到是这样的:
Which I hoped would expand to something like:
static void Unique_23(void) {}
这是行不通的。随着令牌串联,定位宏
字面上处理,结束了扩大为:
That doesn't work. With token concatenation, the positioning macrosare treated literally, ending up expanding to:
static void Unique___LINE__(void) {}
这是可能的吗?
(是的,有一个真正的原因,我想这样做再好也没用,这似乎)。
(Yes, there's a real reason I want to do this no matter how useless this seems).
推荐答案
的问题是,当你有一个宏替换,则preprocessor只会扩大宏递归如果既字符串化操作符 #
也不令牌粘贴运算符 ##
被应用到它。所以,你必须使用间接一些额外的图层,可以使用令牌粘贴运营商递归扩展的参数:
The problem is that when you have a macro replacement, the preprocessor will only expand the macros recursively if neither the stringizing operator #
nor the token-pasting operator ##
are applied to it. So, you have to use some extra layers of indirection, you can use the token-pasting operator with a recursively expanded argument:
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)
#define UNIQUE static void TOKENPASTE2(Unique_, __LINE__)(void) {}
然后, __ LINE __
UNIQUE
(扩建过程中被扩展到行号,因为它不会参与任何#
或 ##
),然后标记粘贴的扩张过程中会发生 TOKENPASTE
。
Then, __LINE__
gets expanded to the line number during the expansion of UNIQUE
(since it's not involved with either #
or ##
), and then the token pasting happens during the expansion of TOKENPASTE
.
还应当指出的是,也 __计数器__
宏,其中每个被评价时间扩展为一个新的整数,以便在需要时具有的多个实例在同一行的 UNIQUE
宏。注: __ __ COUNTER
由MS Visual Studio中,海湾合作委员会(自V4.3),并支持锵,而不是标准的C
It should also be noted that there is also the __COUNTER__
macro, which expands to a new integer each time it is evaluated, in case you need to have multiple instantiations of the UNIQUE
macro on the same line. Note: __COUNTER__
is supported by MS Visual Studio, GCC (since V4.3), and Clang, but is not standard C.
这篇关于与##和__LINE__(带定位宏令牌串联)创建C代码宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!