4

I have two versions of a C++ compiler installed on my computer. One of them recognizes the __COUNTER__ macro and the other does not.

After doing some research to make the program compile in both, I have yet to come across the macro definition for __COUNTER__. Is this some special macro done by the compiler or can I copy the definition for __COUNTER__ into my source code? If I can copy it, what is the code I need?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gibby
  • 458
  • 1
  • 4
  • 14

2 Answers2

10

__COUNTER__ is a built-in in several common compilers. It is not possible to define manually. If you're stuck with a compiler that doesn't support it, your best option might be to run your code through a preprocessor that does support it before feeding it into the compiler.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
2

It's a special macro which has been introduced by Visual Studio and I think is now supported by GCC too.

It basically provides a unique counter over integral numbers which can be used to generate unique identifiers.

From GCC release notes:

A new predefined macro __COUNTER__ has been added. It expands to sequential integral values starting from 0. In conjunction with the ## operator, this provides a convenient means to generate unique identifiers.

If you don't have it available to a compiler you can easily mimic the behavior with a static variable. But I'm not sure what you are compiling so I'm not sure how this counter is used in the code you have available.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • 1
    You can't increment a variable with the preprocessor... how would using a variable work? – Fiddling Bits Dec 25 '13 at 01:50
  • @FiddlingBits I wrote a little hack once that has a `INIT` macro that set `COUNTER=0;`, and another macro which included `COUNTER++;`. It is not fully functional, but it can server pretty well, despite requiring a global variable. – dmckee --- ex-moderator kitten Dec 25 '13 at 02:15
  • 1
    @FiddlingBits: it depends how the actual `__COUNTER__` macro is used inside the code. You could be able to mimic the behavior or not according to how the generated number is used. – Jack Dec 25 '13 at 02:16
  • Do you use `#define` and `#undef` repeatedly? – Fiddling Bits Dec 25 '13 at 02:18
  • @FiddlingBits, Take a look at [Boost's](http://www.boost.org/doc/libs/1_55_0/libs/preprocessor/doc/ref/counter.html). – chris Dec 25 '13 at 02:26
  • @chris Looks interesting, but it doesn't expose the guts, huh? – Fiddling Bits Dec 25 '13 at 02:30
  • @FiddlingBits, Check your installation. It's definitely open source and it's actually interesting how high it can go. – chris Dec 25 '13 at 02:31