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
324 views
in Technique[技术] by (71.8m points)

c - How can we know the caller function's name?

In the C language, __FUNCTION__ can be used to get the current function's name. But if I define a function named a() and it is called in b(), like below:

b()
{
    a();
}

Now, in the source code, there are lots of functions like b() that call a(), e.g. c(), d(), e()...

Is it possible, within a(), to add some code to detect the name of the function that called a()?

Further:

  1. Sorry for the misleading typo. I have corrected it.
  2. I am trying to find out which function calls a() for debugging purposes. I don't know how you do when in the same situation?
  3. And my code is under vxWorks, but I am not sure whether it is related to C99 or something else.
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There's nothing you can do only in a.

However, with a simple standard macro trick, you can achieve what you want, IIUC showing the name of the caller.

void a()
{
    /* Your code */
}

void a_special( char const * caller_name )
{
    printf( "a was called from %s", caller_name );
    a();
}

#define a() a_special(__func__)

void b()
{
    a();
}

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

...