1

In a macro I want to generate a variable with a different name and try to use __LINE__ as a way to differentiate them. A simplified sample:

#define UNIQUE_INT   int prefix##__LINE__

UNIQUE_INT;
UNIQUE_INT;

But it seems that __LINE__ is not expanding as I get "int prefix__LINE__' : redefinition" in the second one.

I suppose that __LINE__ can not be used in a macro definition as if it expanded would do to the line number of the #definition rather than the line of the invocation of the macro, but let me ask just in case someone has something to say.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
tru7
  • 6,348
  • 5
  • 35
  • 59
  • This looks like a terrible idea. Even if you do manage to create variables with names based on line numbers, how do you intend to refer to these variables later on in your code? – r3mainer Jan 29 '16 at 15:19
  • 1
    @squeamishossifrage it's not a terrible idea, in general, it can be quite useful. the point is not that you will refer to a variable again, but rather that you want to ensure that it is constructed and not referred to in the rest of the function, because of some side-effect or debugging. For just int's like this I guess it's useless but probably its just an example. – Chris Beck Jan 29 '16 at 15:20
  • Yes the sample is an oversimplification. As @chrisbeck says there's a good answer. – tru7 Jan 29 '16 at 16:01

1 Answers1

8

The problem is that in the preprocessor, the ## takes place before __LINE__ is expanded. If you add another layer of indirection, you can get the desired result.

For technical reasons you actually need two macros (sometimes if you use this in an existing macro you don't need the second one, it seems...):

#define TOKEN_PASTE(x, y) x##y
#define CAT(x,y) TOKEN_PASTE(x,y)
#define UNIQUE_INT \
  int CAT(prefix, __LINE__)

UNIQUE_INT;
UNIQUE_INT;
Chris Beck
  • 15,614
  • 4
  • 51
  • 87
  • But it doesn't work (gcc 4.9.2). It produces two lines of `int prefix__LINE__;`. – gudok Jan 29 '16 at 15:39
  • It does not work. neither in gcc or with Visual Studio. Same result. – tru7 Jan 29 '16 at 15:57
  • 1
    Sorry, the first version had an error because I copied from my existing code a bit hastily. You need to use two macros, not just one. Actually the guy who posted this duplicate I guess made the same mistake at first: http://stackoverflow.com/questions/1597007/creating-c-macro-with-and-line-token-concatenation-with-positioning-macr... I should have checked for a duplicate before answering anyways. – Chris Beck Jan 29 '16 at 16:00