How to generate random variable names in C++ using macros?

前端 未结 8 2021
别跟我提以往
别跟我提以往 2020-12-01 07:56

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

8条回答
  •  失恋的感觉
    2020-12-01 08:53

    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:

    1. Use leading underscores or similar naming conventions for symbols defined within the macro. This will prevent problems associated with a parameter using the same symbol from occurring.
    2. Only use the input parameters once and always surround them with parentheses. This is the only way to make macros work with expressions as input.
    3. Use the do { ... } while (0) idiom to ensure that the macro is only used as a statement and to avoid other textual replacement problems.

提交回复
热议问题