代码之家  ›  专栏  ›  技术社区  ›  Bharathwaaj

C语言宏预处理中标签的生成

  •  1
  • Bharathwaaj  · 技术社区  · 16 年前

    如何编写调用goto END\label的宏?

    例如:

    #define MY_MACRO() \
    //How to define goto END_##function_name label??
    
    my_function()
    {
        MY_MACRO();
    
    END_my_function:
       return;
    }
    

    myu宏应该简单地替换为行

    goto END_my_function;
    
    3 回复  |  直到 16 年前
        1
  •  3
  •   lhf    16 年前

    我认为这是办不到的。即使有些编译器定义 __FUNCTION__ 或 __func__

    但是,请注意,每个函数不需要单独的标签:您可以使用 END 对于所有函数,只需编写 goto END .

        2
  •  3
  •   bstpierre Edgar Aviles    16 年前

    预处理器不知道它在哪个函数中。但是您可以接近--您必须将函数名传递给这个宏

    #include <stdio.h>
    
    #define GOTO_END(f) goto f ## _end
    
    void foo(void)
    {
       printf("At the beginning.\n");
    
       GOTO_END(foo);
    
       printf("You shouldn't see this.\n");
    
      foo_end:
       printf("At the end.\n");
       return;
    }
    
    int main()
    {
       foo();
    }
    
        3
  •  1
  •   Praetorian Luchian Grigore    16 年前

    使用 token concatenation

    #define MY_MACRO( function_name ) END_ ## function_name