RedX
RedX

Reputation: 15185

__COUNTER__ in variable name

I have seen this question:

How to generate random variable names in C++ using macros?

with the following answer: https://stackoverflow.com/a/1675203/551045

And I've tried to implement it in clang.

Here is my declaration:

#define TRACE(stream) FuncTrace x#__COUNTER__ (llvm::errs(), "hallo", 1)

I tried all variations x##__COUNTER__; x ## __COUNTER__ and so on but none seem to work.

Could this be a clang bug? The clang help page says it has the __COUNTER__ macro.

In the end the macro I need something like this:

#define TRACE(stream) FuncTrace x#__COUNTER__ (stream, __FUNCTION__, __LINE__)

Upvotes: 3

Views: 3388

Answers (1)

kennytm
kennytm

Reputation: 523614

  1. To concatenate two tokens into one you use the ## operator. The # operator is used to turn a token into a string.

  2. x ## __COUNTER__ will just produce x__COUNTER__. You need to fully expand __COUNTER__ first. One possible method is add a few more indirections, e.g.

    #define YTRACE(x, y) FuncTrace x##y (llvm::errs(), __FUNCTION__, __LINE__)
    #define XTRACE(x, y) YTRACE(x, y)
    #define TRACE(x) XTRACE(x, __COUNTER__)
    

Upvotes: 12

Related Questions