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, ...);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…