简体   繁体   English

在 C 的宏中重新定义的标签

[英]Labels redefined in Macro in C

Trying to use goto labels in a C macro (running MSVC) but if the macro is called multiple times in the same caller function, C2045 label redefined errors appear.尝试在 C 宏(运行 MSVC)中使用 goto 标签,但如果在同一个调用者 function 中多次调用该宏,则会出现 C2045 ZD304BA20E96D87413411588EEABA 重新定义的错误。

I've tried using __label__ from this example: https://www.geeksforgeeks.org/local-labels-in-c/ but that label keyword is probably gcc only because MSVC reports label undefined. I've tried using __label__ from this example: https://www.geeksforgeeks.org/local-labels-in-c/ but that label keyword is probably gcc only because MSVC reports label undefined.

I understand it's really obfuscated and silly but I'm writing a transpiler to convert MASM code into C.我知道这真的很混乱和愚蠢,但我正在编写一个转译器来将 MASM 代码转换为 C。 In MASM, labels are defined locally using the LOCAL directive, __label__ is used by GCC, but what does MSVC offer as a solution?在 MASM 中,标签是使用 LOCAL 指令在本地定义的,__label__ 由 GCC 使用,但 MSVC 提供了哪些解决方案?

#include <stdint.h>
#include <stdio.h>

#define     Loopy(AA) {              \
   RTSZ_0:;                          \
   if (AA >= 5) { goto RTSZ_1; }     \
   AA += 1;                          \
   goto RTSZ_0;                      \
   RTSZ_1:;                          \
}                               

int main()
{
    int AA = 0;

    Loopy(AA);
    Loopy(AA);

    return 0;
}

I was expecting the goto labels to be assigned a unique label so that when included multiple times, there would be no redefinition errors.我期望 goto 标签被分配一个唯一的 label 以便在多次包含时不会出现重新定义错误。

Is there a C keyword that can be applied to the macro or a workaround?是否有可以应用于宏的 C 关键字或解决方法? Something like:就像是:

            __Uniquelabel__       RTSZ_0; \
            __Uniquelabel__       RTSZ_1; \

Any ideas?有任何想法吗? Thanks!谢谢!

currently looking into using this code:目前正在研究使用此代码:

 #define S1(x) #x #define S2(x) S1(x) #define RTSZ "RTSZ_" S2(__LINE__) ":"

Indeed something along the above lines can be used to generate unique labels, as long as there's not more than one macro invocation per source line:实际上,只要每个源代码行不超过一个宏调用,就可以使用上述内容生成唯一标签:

#define RTSZ(i) RTSZ1(i, __LINE__)
#define RTSZ1(i, l) RTSZ2(i, l)
#define RTSZ2(i, l) RTSZ_##i##_##l

#define     Loopy(AA) {              \
   RTSZ(0):                          \
   if (AA >= 5) { goto RTSZ(1); }    \
   AA += 1;                          \
   goto RTSZ(0);                     \
   RTSZ(1): ;                        \
}

The intermediate RTSZ1() macro serves to expand the __LINE__ macro, similar to the S2() in your approach.中间RTSZ1()宏用于扩展__LINE__宏,类似于您方法中的S2()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM