0

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!

S. Arquet
  • 29
  • 4
  • Why do you want to do this? What actual problem are you trying to solve using this technique? – NathanOliver Sep 23 '21 at 16:09
  • You could use a real compile time counter instead of a macro. – Mechap Sep 23 '21 at 16:21
  • @NathanOliver - I added the usage case to the original post. – S. Arquet Sep 23 '21 at 19:18
  • @Mechap - do you have any example of how that would work? – S. Arquet Sep 23 '21 at 19:18
  • In this case, I think you could just do `#define name_of_static_variable __FILE__##__LINE__` That would let you not have to change the code base as well as create the N unique names that you need. – NathanOliver Sep 23 '21 at 19:31
  • @NathanOliver - that doesn't work, as I end up with the full pathname of the file on my hard drive and it can't become a variable name. – S. Arquet Sep 23 '21 at 19:39
  • Write a quick program that goes through each cpp file and renames any occurrence of `name_of_static_variable` to be some unique name your program generates for each file? – NathanOliver Sep 23 '21 at 19:40

0 Answers0