简体   繁体   English

每个源文件一次扩展__COUNTER__宏

[英]Expand __COUNTER__ macro once per source file

I'm trying to write a macro that will expand the __COUNTER__ macro only once per source file. 我正在尝试编写一个宏,每个源文件只能扩展一次__COUNTER__宏。 I understand fully how macros work with their expansion but I'm having difficulty with this one. 我完全了解宏如何与它们的扩展一起工作,但是我对此很难。 I want to expand the __COUNTER__ macro once at the top of the file and then each reference to that define will not expand the __COUNTER__ to it's next number. 我想在文件顶部扩展一次__COUNTER__宏,然后对该定义的每个引用都不__COUNTER__扩展为下一个数字。

So I want to fully expand __COUNTER__ into a single value and then use that one value consistently through the current working source file. 因此,我想将__COUNTER__完全扩展为一个值,然后在当前工作的源文件中一致地使用该值。

I can only use features that are available to C . 我只能使用C可用的功能。

The __COUNTER__ extension (I suppose you are using a compiler from the gcc family) is too restricted for such a use. __COUNTER__扩展名(我想您正在使用gcc系列的编译器)对于这种用法太受限制了。 The difficulty is that if you put it into another macro, say TOTO , it is not expanded at definition but only at its use. 困难在于,如果将其放入另一个宏(例如TOTO ,则它不会在定义时扩展,而只会在使用时扩展。 So each invocation of TOTO will give rise to a new value of the counter. 因此,每次调用TOTO都会产生一个新的计数器值。

In P99 I have a portable replacement for this, that achieves that goal with some #include hackery. P99中,我有一个便携式的替代品,可以通过一些#include黑客实现这一目标。 P99_FILEID is then an per file identifier, and P99_LINEID an ID that should be unique for all lines in your compilation unit (but use with care). 然后, P99_FILEID是每个文件的标识符, P99_LINEID是一个ID,对于您的编译单元中的所有行都应唯一(但要小心使用)。

Another alternative if you just need a compile time constant and nothing in the preprocessor itself would be to use the counter in an enumeration constant. 如果您只需要一个编译时间常数,而预处理器本身没有任何东西,则另一种选择是在枚举常数中使用计数器。

enum { toto_id = __COUNT__, }; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM