I’m trying to generate a unique variable name with a MACRO, but then immediately reference it again in the same code module, and I cannot figure out if it’s possible.
I am using __ COUNTER __ because I cannot use __ LINE __; this appears in multiple .cpp modules and line numbers could be the same.
For example:
#define MY_VAR JOIN( myVar, __COUNTER__ )
#define JOIN( symbol1, symbol2 ) _DO_JOIN( symbol1, symbol2 )
#define _DO_JOIN( symbol1, symbol2 ) symbol1##symbol2
int MY_VAR = 5;
void someFunction(&MY_VAR)
{
...
}
What happens is that COUNTER is incremented twice, so the second occurrence does not match the first one.
This post seems to imply that it’s not possible in some of the comments; however, as it is rather old, I wonder if a solution has occurred to anyone:
How to generate random variable names in C++ using macros?
EDIT: (add explanation of usage case) I have inherited some old code that I need to port. There are several hundred .cpp files that each declare a static variable (outside of any class), and since they were originally auto-generated by some script, they all use the same variable name. This is not a problem since the static variable normally is only inside that .cpp module. that variable is then passed to an object creation function, so it is used TWICE.
However, I am turning it into a JUCE (C++ framework) module, and as such all the .cpp files are essentially #included into one .cpp file; hence, all of these same-named variables cause redefined symbol errors.
I was looking for a macro that would automatically generate a unique name within each .cpp file, however as I said the variable is referenced twice in each file. Hope that makes some sense!