如何通过宏声明变量?
首先,我使用MS的Visual Studio并使用C语言。
最近我需要用一个相同的语句来声明变量,就像宏一样。
然而,如您所知,我只能声明一个具有相同名称的变量。
例如,这是不可能的。
int iVar1;
int iVar1; // this is not possible.
所以我想到了宏包括 __LINE__ ,如果我可以使用这个预定义的宏,我可以通过一个宏语句声明很多变量。
但制作起来很困难。
我做了这样的宏。
#define MY_LINE_VARIABLE int g_iLine##__LINE__##Var = 0;
但编译后,我可以得到这个名为“g_iLine_LINE_Var”的变量,而不是“g_iLine123Var”
我想知道这是可能的,我该如何做到这一点。
此外,如果可能的话,我需要使用 __FILE__ 宏。但这个宏可能会随着字符串数据而改变。所以我不能确定。
任何建议都会有所帮助。
提前感谢您的帮助。
first of all, I'm using MS's Visual Studio and using C language.
Recently I need to declare variables with just one same statement which likes a macro.
However as you know, I can declare just one variable which have same name.
for example, this is not possible.
int iVar1;
int iVar1; // this is not possible.
so I thought about macros include __LINE__ , if I can use this predefined macro, I can declare lots of variables via just one macro statement.
But it was difficult to make.
I made macro like this.
#define MY_LINE_VARIABLE int g_iLine##__LINE__##Var = 0;
but after compile, i could get this variable named 'g_iLine_LINE_Var' instead of 'g_iLine123Var'
I want to know that is this possile, and how can i make it.
Furthermore, I need to use __FILE__ macro if possible. but this macro might be changed with string data. so I can not be sure.
Any advice will be helpful.
Thank you for your help in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 @Chris Lutz 所说,可能有更好的方法来实现你想要的。考虑询问你想要实现什么目标。
但如果您只是好奇,可以这样做:
As @Chris Lutz has rightly said that, there might be a better way to accomplish what you want. Consider asking what you want to achieve.
But if you are just curious, this is the way to do:
来自此链接:
因此,在您的情况下:
MY_VARIABLE_LINE
转换为int g_iLine__LINE__Var;
。但现在__LINE__
不再是有效的标记,并且不再被视为预定义的宏。Aditya 的代码是这样工作的:
MY_VARIABLE_LINE
转换为decl(__LINE__)
,再转换为var(123)
,再转换为int giLine123var = 0
。编辑:这是针对 GNU C 的
From this link :
So in your case :
MY_VARIABLE_LINE
is converted toint g_iLine__LINE__Var;
. But now__LINE__
is not a valid token anymore and is not treated as a predefined macro.Aditya's code works like this:
MY_VARIABLE_LINE
is converted todecl(__LINE__)
which is converted tovar(123)
which is converted toint giLine123var = 0
.Edit: This is for GNU C