Why is a level of indirection needed for this concatenation macro?

 ̄綄美尐妖づ 提交于 2019-11-27 04:33:10

问题


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

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


回答1:


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 be prefix__LINE__.

it's useful to read this answer too, and this thread.



来源:https://stackoverflow.com/questions/19666142/why-is-a-level-of-indirection-needed-for-this-concatenation-macro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!