Felix Jones
Felix Jones

Reputation: 330

Expand __COUNTER__ macro once per source file

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.

Upvotes: 1

Views: 1302

Answers (1)

Jens Gustedt
Jens Gustedt

Reputation: 78953

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__, }; 

Upvotes: 2

Related Questions