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

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

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

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

谢谢你帮助我:)

您需要一个遵循C99标准或更高版本的C编译器。 有一个名为__func__的预定义标识符__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 

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

 #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() 。 这是我的function和输出:

 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'