简体   繁体   English

可以计算预处理器宏吗?

[英]Counting preprocessor macro possible?

Is it possible to create a C preprocessor macro that evaluates to an increasing number depending on how often it was called? 是否可以创建一个C预处理器宏,根据调用频率来评估增加的数量? It should be compile-time only. 它应该只是编译时。

I'd like something like: 我喜欢这样的东西:

#define INCREMENT() ....
#define INCRVALUE ....

INCREMENT()
INCREMENT()
i = INCRVALUE;
// ...
INCREMENT()
// ...
j = INCRVALUE;

and afterwards i == 2 and j == 3. 然后我= = 2和j == 3。

The C pre-processor works with text. C预处理器使用文本。 It can't do any kind of arithmetic because it does not know how and even if it did, you can't assign to rvalues like literals (eg 5 = 5+1 or ++5 ). 它不能做任何类型的算术,因为它不知道如何,即使它做了,你也不能分配像文字这样的rvalues(例如5 = 5+1++5 )。

A static variable would be much better. static变量会好得多。

GCC provides a macro, __COUNTER__ , which expands to an integer representing how many times it's been expanded but that's not ISO C. GCC提供了一个宏__COUNTER__ ,它扩展为一个整数,表示它被扩展了多少次,但不是ISO C.

#define CNT __COUNTER__
#define INCREMENT() CNT

INCREMENT();
INCREMENT();
int i = CNT;  
// i = 2

Boost may help if you need it to be portable. 如果您需要便携式, Boost可能会有所帮助。

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

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