Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

c - Get called function name as string

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

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].

Thanks for helping me :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...