How can we know the caller function's name?

后端 未结 10 1630
北海茫月
北海茫月 2020-12-02 10:26

In the C language, __FUNCTION__ can be used to get the current function\'s name. But if I define a function named a() and it is called

10条回答
  •  醉话见心
    2020-12-02 11:18

    Try this:

    void a();
    
    #ifdef DEBUG
    #  define a() a_debug(, __FUNCTION__)
    void a_debug(, const char * calledby);
    #endif
    
    void b(void)
    {
      a();
    }
    
    #ifdef DEBUG
    #  undef a
    #endif
    
    void a()
    {
      printf("'%s' called\n", __FUNCTION__);
    }
    
    #ifdef DEBUG
    void a_debug(, const char * calledby)
    {
      printf("'%s' calledby '%s'", __FUNCTION__, calledby);
      a();
    }
    #endif
    

    If for example is int i, double d, void * p then is i, d, p.


    Or (less evil ;->> - but more code modding, as each call to a() needs to be touched):

    void a((    
    #ifdef DEBUG
      , const char * calledby
    #endif
      );
    
    void a((    
    #ifdef DEBUG
      , const char * calledby
    #endif
      )
    {
    #ifdef DEBUG
      printf("'%s' calledby '%s', __FUNCTION__, calledby);
    #endif
      ...
    }
    
    ...
    
    void b(void)
    {
        a(
    #ifdef DEBUG
          , __FUNC__
    #endif
        );
    }
    

    __FUNCTION__ is available on GCC (at least?), if using a different C99 compiler replace it with __func__.

提交回复
热议问题