3

I am trying to use the __COUNTER__ macro to generate unique variable names in my code. But the macro doesn't seem to work. I may be using it the wrong way. Please provide me pointers or suggestion to what I am doing wrong.

#define DUMB_MACRO() ht##__COUNTER__

should give me ht0,ht1....

The way I am calling it in the main file is

DUMB_MACRO();

But the compiler says it doesn't resolve the symbol ht__COUNTER__ if I try using ht0 variable.

I also tried using the __CONCAT macro but I cannot pass variable into it.

For example:
__CONCAT(ht,1) works and gives me ht1 but __CONCAT(ht,i) where i is a variable holding saying the value 1 doesn't work because its value is not known at compile time.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    Be aware that `__COUNTER__` is a GNU extension; it's not necessarily portable to compilers other than g++ (clang++ seems to support it as well). (Unless it was added to the standard very recently). – Keith Thompson Dec 22 '14 at 23:23
  • It wasn't. http://stackoverflow.com/questions/652815/has-anyone-ever-had-a-use-for-the-counter-pre-processor-macro – 2501 Dec 22 '14 at 23:25

1 Answers1

5

You have to expand the macro:

#define MACRO3(s) ht##s
#define MACRO2(s) MACRO3(s)
#define MACRO MACRO2(__COUNTER__)

int MACRO ;  //ht0
int MACRO ;  //ht1
2501
  • 25,460
  • 4
  • 47
  • 87