为什么这个串联宏需要一个间接级别? [英] Why is a level of indirection needed for this concatenation macro?

查看:16
本文介绍了为什么这个串联宏需要一个间接级别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 一篇有趣的小博文 解释了如何使用行号在宏中生成(半)唯一名称:

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:

  1. 为什么 LINE_NAME 宏即使在文件中声明了 JOIN 之后也能工作?我认为 C 预处理器进行了线性传递,因此需要根据依赖关系定义宏,就像在使用 C 函数之前需要定义它们一样.
  2. 为什么必须同时使用 JOIN_DO_JOIN 宏才能获得正确的结果?在宏中使用这种间接级别似乎很奇怪.
  1. Why does the LINE_NAME macro even work if JOIN 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.
  2. 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.

我觉得这两个问题的答案是相关的,并且与 C 预处理器评估宏的方式有关.(但是,我对宏如何工作的直觉显然是错误的,因为我什至不认为这个例子是有效的.)

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.)

推荐答案

为什么 LINE_NAME 宏即使在文件中声明 JOIN 之后也能工作?

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.

为什么必须同时使用 JOIN 和 _DO_JOIN 宏才能获得正确的结果?在宏中使用这种间接级别似乎很奇怪.

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.

因为__LINE__本身就是一个宏,所以需要两级扩展.

Because __LINE__ itself is a macro, it needs two level expanding.

否则输出不是prefix1234,而是prefix__LINE__.

阅读 this answer这个线程.

这篇关于为什么这个串联宏需要一个间接级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆