Get called function name as string

前端 未结 2 2007
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 08:13

I\'d like to display the name of a function I\'m calling. Here is my code

void (*tabFtPtr [nbExo])(); // Array of function pointers
int i;
for (i = 0; i <         


        
2条回答
  •  眼角桃花
    2020-12-09 09:17

    You need a C compiler that follows the C99 standard or later. There is a pre-defined identifier called __func__ which does what you are asking for.

    void func (void)
    {
      printf("%s", __func__);
    }
    

    Edit:

    As a curious reference, the C standard 6.4.2.2 dictates that the above is exactly the same as if you would have explicitly written:

    void func (void)
    {
      static const char f [] = "func"; // where func is the function's name
      printf("%s", f);
    }
    

    Edit 2:

    So for getting the name through a function pointer, you could construct something like this:

    const char* func (bool whoami, ...)
    {
      const char* result;
    
      if(whoami)
      {
        result = __func__;
      }
      else
      {
        do_work();
        result = NULL;
      }
    
      return result;
    }
    
    int main()
    {
      typedef const char*(*func_t)(bool x, ...); 
      func_t function [N] = ...; // array of func pointers
    
      for(int i=0; i

提交回复
热议问题