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