how can i declare variables via macros?

Darpangs picture Darpangs · Aug 5, 2011 · Viewed 13.5k times · Source

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.

Answer

A. K. picture A. K. · Aug 5, 2011

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:

#define var(z) int g_iLine##z##var = 0
#define decl(x) var(x)
#define MY_LINE_VARIABLE        decl(__LINE__)
MY_LINE_VARIABLE;
MY_LINE_VARIABLE;