gpt4 book ai didi

c - 获取被调用的函数名称作为字符串

转载 作者:太空狗 更新时间:2023-10-29 16:25:16 24 4
gpt4 key购买 nike

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

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__ 的预定义标识符,它可以满足您的要求。

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, ...);
}
}

关于c - 获取被调用的函数名称作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15349761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com