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
Generating unique names in the preprocessor is difficult. The closest you can get is to mangle __FILE__
and __LINE__
into the symbol as popcnt suggests. If you really need to generate unique global symbol names, then I would follow his suggestion about using something like M4 or a Perl script in your build system instead.
You might not need unique names. If your macro can impose a new scope, then you can use the same name since it will simply shadow other definitions. I usually follow the common advice of wrapping macros in do { ... } while (0)
loops. This only works for macros which are statements - not expressions. The macro can update variables using output parameters. For example:
#define CALC_TIME_SINCE(t0, OUT) do { \
std::time_t _tNow = std::time(NULL); \
(OUT) = _tNow - (t0); \
} while (0)
If you follow a few rules, you are usually pretty safe:
do { ... } while (0)
idiom to ensure that the macro is only used as a statement and to avoid other textual replacement problems.