1
votes

I'm trying to write a macro that will expand the __COUNTER__ macro only once per source file. I understand fully how macros work with their expansion but I'm having difficulty with this one. I want to expand the __COUNTER__ macro once at the top of the file and then each reference to that define will not expand the __COUNTER__ to it's next number.

So I want to fully expand __COUNTER__ into a single value and then use that one value consistently through the current working source file.

I can only use features that are available to C.

1
Template metaprogramming, you can "generate" IDs running code at...compile time. - Adriano Repetti
I am limited to using only C so this solution must be on the preprocessor - Felix Jones
Does the value need to be available at compile time? Or can it wait until runtime? - Drew McGowen
Must be compile time. - Felix Jones

1 Answers

2
votes

The __COUNTER__ extension (I suppose you are using a compiler from the gcc family) is too restricted for such a use. The difficulty is that if you put it into another macro, say TOTO, it is not expanded at definition but only at its use. So each invocation of TOTO will give rise to a new value of the counter.

In P99 I have a portable replacement for this, that achieves that goal with some #include hackery. P99_FILEID is then an per file identifier, and P99_LINEID an ID that should be unique for all lines in your compilation unit (but use with care).

Another alternative if you just need a compile time constant and nothing in the preprocessor itself would be to use the counter in an enumeration constant.

enum { toto_id = __COUNT__, };