How can we know the caller function's name?

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

You can do it with a gcc builtin.

void * __builtin_return_address(int level)

The following way should print the immediate caller of a function a().

Example:

a() {
    printf ("Caller name: %pS\n", __builtin_return_address(0));
}

Try this:

void a(<all param declarations to a()>);

#ifdef DEBUG
#  define a(<all params to a()>) a_debug(<all params a()>, __FUNCTION__)
void a_debug(<all params to a()>, const char * calledby);
#endif

void b(void)
{
  a(<all values to a()>);
}

#ifdef DEBUG
#  undef a
#endif

void a(<all param declarations to a()>)
{
  printf("'%s' called\n", __FUNCTION__);
}

#ifdef DEBUG
void a_debug(<all param declarations to a()>, const char * calledby)
{
  printf("'%s' calledby '%s'", __FUNCTION__, calledby);
  a(<all params to a()>);
}
#endif

If for example <all param declarations to a()> is int i, double d, void * p then <all params to a()> is i, d, p.


Or (less evil ;->> - but more code modding, as each call to a() needs to be touched):

void a((<all params of normal a()>    
#ifdef DEBUG
  , const char * calledby
#endif
  );

void a((<all params of normal a()>    
#ifdef DEBUG
  , const char * calledby
#endif
  )
{
#ifdef DEBUG
  printf("'%s' calledby '%s', __FUNCTION__, calledby);
#endif
  ...
}

...

void b(void)
{
    a(<all params of normal a()>
#ifdef DEBUG
      , __FUNC__
#endif
    );
}

__FUNCTION__ is available on GCC (at least?), if using a different C99 compiler replace it with __func__.

Tags:

C