how can i declare variables via macros?

15,036

Solution 1

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;

Solution 2

From this link :

After the preprocessor expands a macro name, the macro's definition body is appended to the front of the remaining input, and the check for macro calls continues. Therefore, the macro body can contain calls to other macros.

So in your case :

MY_VARIABLE_LINE is converted to int 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 to decl(__LINE__) which is converted to var(123) which is converted to int giLine123var = 0.

Edit: This is for GNU C

Share:
15,036
Darpangs
Author by

Darpangs

6 years experienced developer. I have developed usermode and kernelmode applications on Windows. It was focused on information security.

Updated on July 07, 2022

Comments

  • Darpangs
    Darpangs almost 2 years

    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.

  • Darpangs
    Darpangs over 12 years
    thank you for your help!. I'm pretty newbie about macros. so your commnet will be helpful to me.
  • Darpangs
    Darpangs over 12 years
    Thank you for your explaining.