[英]How to get the last value of __COUNTER__
I have a macro that does something similar to the following:我有一个类似于以下内容的宏:
#define MAKE_VALS(...) \
int val1 = 0; \
int val2 = 0; \
:
if(val1 == val2) \
{ \
...
}
and I need to use it multiple times within a single function.我需要在单个 function 中多次使用它。 The trouble is, using it multiple times causes multiple definition errors due to multiple definitions of val1 and val2.
麻烦的是,由于val1和val2的多次定义,多次使用会导致多次定义错误。
Using __COUNTER__
with ##
would solve the problem, but I can't see how to get the correct variable names for the if statement?将
__COUNTER__
与##
一起使用可以解决问题,但我看不到如何为 if 语句获取正确的变量名称? I can't use __COUNTER__
again because I'd get the next value.我不能再次使用
__COUNTER__
因为我会得到下一个值。 I need a way to get the last value of __COUNTER__
.我需要一种方法来获取
__COUNTER__
的最后一个值。 Can it be done?可以做到吗?
PS. PS。 I don't want to surround it with
{}
s to fix the problem.我不想用
{}
包围它来解决问题。 I've simplified the real problem here and using {}
s causes other problems (that aren't important to what I'm asking).我在这里简化了真正的问题,使用
{}
会导致其他问题(这对我的要求并不重要)。
For whatever the purpose of this is, you can achieve that using several levels of macros:无论出于何种目的,您都可以使用多个级别的宏来实现:
#define MAKE_VALS(...) MAKE_VALS1(..., __COUNTER__)
#define MAKE_VALS1(..., counter) MAKE_VALS2(..., counter)
#define MAKE_VALS2(..., counter) \
int val1##counter = 1; int val2##counter = 2; \
val1##counter = whatever; val2##counter = hunoz;
This way, you can use MAKE_VALS
more than once in the same scope, and every call will create a new set of variables.这样,您可以在同一个 scope 中多次使用
MAKE_VALS
,并且每次调用都会创建一组新的变量。 Note that without MAKE_VALS1
, your variables would be named val1__COUNTER__
and so on, and the extra level makes it the actual number.请注意,如果没有
MAKE_VALS1
,您的变量将被命名为val1__COUNTER__
等等,额外的级别使其成为实际数字。
It's a nice exercise in macro writing, but I agree with the guys before me who questioned if this is the right way to achieve whatever you're trying to achieve.这是宏编写的一个很好的练习,但我同意我之前的人的观点,他们质疑这是否是实现你想要实现的任何目标的正确方法。 But enough has been said about that, so I hope this solves your problem.
但是关于这一点已经说得够多了,所以我希望这能解决你的问题。
#define MAKE_VALS(m, n, ...) \
int val ## m = 0; \
int val ## n = 0; \
:
if(val ## m == val ## n) \
{ \
...
}
Use:利用:
MAKE_VALS(__LINE__,
__LINE__, ... ); //second __LINE__ on next line
Put second __LINE__
on next line to avoid having same value for both m
and n
.将第二个
__LINE__
放在下一行,以避免m
和n
具有相同的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.