将被调用的函数名称作为字符串

时间:2013-03-11 22:16:24

标签: c

我想显示我正在调用的函数的名称。这是我的代码

void (*tabFtPtr [nbExo])(); // Array of function pointers
int i;
for (i = 0; i < nbExo; ++i)
{
    printf ("%d - %s", i, __function__);
}

我使用__function__作为例子,因为它与我想要的非常接近,但我想显示tabFtPtr [nbExo]指向的函数的名称。

感谢您帮助我:)

2 个答案:

答案 0 :(得分:29)

您需要一个符合C99标准或更高版本的C编译器。有一个名为__func__的预定义标识符可以满足您的要求。

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

编辑:

作为一个奇怪的参考,C标准6.4.2.2规定上述内容与您明确写明的内容完全相同:

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

编辑2:

因此,为了通过函数指针获取名称,您可以构造类似这样的内容:

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<N; i++)
  {
    printf("%s", function[i](true, ...);
  }
}

答案 1 :(得分:2)

我不确定这是你想要的,但你可以这样做。声明一个结构来保存函数名和地址,以及一个函数数组:

#define FNUM 3

struct fnc {
    void *addr;
    char name[32];
};

void (*f[FNUM])();
struct fnc fnames[FNUM];

通过函数名称手动在代码中初始化它们,例如

    fnames[0] = (struct fnc){foo1, "foo1"}; // function address + its name
    fnames[1] = (struct fnc){foo2, "foo2"};
    fnames[2] = (struct fnc){foo3, "foo3"};

创建一个搜索数组的函数,例如

char *getfname(void *p)
{
        for (int i = 0; i < FNUM; i++) {
                if (fnames[i].addr == p)
                        return fnames[i].name;
        }
        return NULL;
}

我对此进行了快速测试。我在main中初始化了数组,并调用了foo1()。这是我的功能和输出:

void foo1(void)
{
    printf("The pointer of the current function is %p\n", getfnp(__func__));
    printf("The name of this function is %s\n", getfname(getfnp(__func__)));
    printf("The name of the function at pointer f[2] (%p) is '%s'\n", f[2],
        getfname(f[2]));    
}

The pointer of the current function is 0x400715
The name of this function is foo1
The name of the function at pointer f[2] (0x40078c) is 'foo3'

或者,更一般地说:

void foo2(void)
{
    for (int i = 0; i < FNUM; i++) {
        printf("Function f[%d] is called '%s'\n", i, getfname(f[i]));
    }
}

Function f[0] is called 'foo1'
Function f[1] is called 'foo2'
Function f[2] is called 'foo3'