被调用函数名作为字符串 [英] Get called function name as string

查看:107
本文介绍了被调用函数名作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要展示我调用一个函数的名称。这里是我的code

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 < nbExo; ++i)
{
    printf ("%d - %s", i, __function__);
}

我用 __功能__ 作为个例,因为它是pretty接近从想我,但我想显示由<$ C指向的函数的名称$ C> tabFtPtr [nbExo] 。

I used __function__ as an exemple because it's pretty close from what I'd like but I want to display the name of the function pointed by tabFtPtr [nbExo].

感谢您帮助我:)

推荐答案

您需要遵循C99标准或更高版本的C编译器。有一个名为 __ __ FUNC 它做什么你所要求的。

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__);
}

编辑:

作为一个好奇的参考,C标准6.4.2.2规定,上面的是完全一样的,如果你会明确写入:

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

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

这篇关于被调用函数名作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆