为什么需要这个级联的宏观间接的级别? [英] Why is a level of indirection needed for this concatenation macro?
问题描述
我发现一个有趣的小博客文章,说明如何通过使用行号以产生一个宏(半)唯一名称:
//使用魔法!创建一个使用行数的唯一名称
LINE_NAME的#define(preFIX)JOIN(preFIX,__LINE__)
#定义JOIN(符号1,symbol2)_DO_JOIN(符号1,symbol2)
#定义_DO_JOIN(符号1,symbol2)符号1 ## symbol2
有两件事情在这里,真的让我困惑:
- 为什么如果
加入
终止后,宣布该文件中的LINE_NAME
宏甚至工作?我以为的C preprocessor做了线性调整,因而需要在宏基于依赖加以界定,就像C函数必须要在使用之前被定义。 - 为什么必要的,以便得到正确的结果同时使用
加入
和_DO_JOIN
宏?在宏此级别的间接似乎很奇怪。
我有一种感觉,答案既这些问题是相关的,并且有,在C preprocessor评估宏的方式做。 (但是,我对宏如何工作的直觉是显然的路要走,因为我甚至不认为例子是有效的。)
为什么如果JOIN后声明文件中的宏LINE_NAME甚至工作?
块引用>宏都没有的功能,当你打电话给他们的编译器扩展了他们,并有编译器在使用点知道的所有定义的宏。
为什么要同时使用,以获得正确的结果JOIN和_DO_JOIN宏?在宏此级别的间接似乎很奇怪。
块引用>由于
__ __ LINE
本身是一个宏观的,它需要两级膨胀。否则输出不是
prefix1234
这将是prefix__LINE __
。的是非常有用的阅读这个答案太 的
I found an interesting little blog post that explains how to generate (semi) unique names in a macro by using the line number:
// Do magic! Creates a unique name using the line number #define LINE_NAME( prefix ) JOIN( prefix, __LINE__ ) #define JOIN( symbol1, symbol2 ) _DO_JOIN( symbol1, symbol2 ) #define _DO_JOIN( symbol1, symbol2 ) symbol1##symbol2
There are two things here that really confuse me:
- Why does the
LINE_NAME
macro even work ifJOIN
is declared after it in the file? I thought the C preprocessor did a linear pass, and thus would need the macros to be defined based on dependency, just like C functions need to be defined before they're used.- Why is it necessary to use both the
JOIN
and_DO_JOIN
macros in order to get the correct result? Having this level of indirection in the macros seems very strange.I have a feeling that the answers to both those questions are related, and have to do with the way that the C preprocessor evaluates macros. (However, my intuition on how macros work is apparently way off since I didn't even think that the example was valid.)
解决方案Why does the LINE_NAME macro even work if JOIN is declared after it in the file?
Macros are not functions, when you call them compiler expands them, and there compiler at the using point knows about all defined macros.
Why is it necessary to use both the JOIN and _DO_JOIN macros in order to get the correct result? Having this level of indirection in the macros seems very strange.
Because
__LINE__
itself is a macro, it needs two level expanding.Otherwise the output is not
prefix1234
it will beprefix__LINE__
.it's useful to read this answer too.
这篇关于为什么需要这个级联的宏观间接的级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!