I\'m creating a macro in C++ that declares a variable and assigns some value to it. Depending on how the macro is used, the second occurrence of the macro can override the v
Try the following:
// This is some crazy magic that helps produce __BASE__247
// Vanilla interpolation of __BASE__##__LINE__ would produce __BASE____LINE__
// I still can't figure out why it works, but it has to do with macro resolution ordering
#define PP_CAT(a, b) PP_CAT_I(a, b)
#define PP_CAT_I(a, b) PP_CAT_II(~, a ## b)
#define PP_CAT_II(p, res) res
#define UNIQUE_NAME(base) PP_CAT(base, __COUNTER__)
__COUNTER__
is rumored to have portability issues. If so, you can use __LINE__
instead and as long as you aren't calling the macro more than once per line or sharing the names across compilation units, you will be just fine.
Instead of having the preprocesser create a name, you could possibly let the macro user give you a name.
#define MY_MACRO(varname) int varname = getCurrentTime();