Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset __COUNTER__ macro to zero

Tags:

c++

is it possible to reset the __COUNTER__ macro at the start of a header file to make its evaluation within the header file consistent over several compile units?

like image 751
user5024425 Avatar asked Apr 29 '16 07:04

user5024425


3 Answers

How about an enum?

enum { COUNTER_BASE = __COUNTER__ };

#define LOCAL_COUNTER (__COUNTER__ - COUNTER_BASE)
like image 83
Michael Avatar answered Oct 18 '22 03:10

Michael


You can set BASE to __COUNTER__ at the top of your header file, and then use __COUNTER__ - BASE later on.

However, do this after you've included all necessary headers, because else thee result would depend on the use of __COUNTER__ within the header guards of those nested include files.

like image 28
MSalters Avatar answered Oct 18 '22 01:10

MSalters


No, there is no way to reset that value.

Take a look at the GCC source that increments the counter:

case BT_COUNTER:
    if (CPP_OPTION (pfile, directives_only) && pfile->state.in_directive)
    cpp_error (pfile, CPP_DL_ERROR,
        "__COUNTER__ expanded inside directive with -fdirectives-only");
    number = pfile->counter++;
    break;

And if you look arount this library, nowhere is the counter modified again. It is default initialized to 0 and then incremented at every use.

Note that the pfile, where the counter variable resides, represents the the preprocessor input, that in this case is the current compilation unit, not the actual file.

like image 4
rodrigo Avatar answered Oct 18 '22 01:10

rodrigo