我们如何知道调用函数的名称?
在C语言中, __FUNCTION__
可用于获取当前函数的名称。 但是,如果我定义一个名为a()的函数,并在b()中调用它,如下所示:
b() { a(); }
现在,在源代码中,有很多函数如b()调用a(),例如c(),d(),e()……
是否可以在()中添加一些代码来检测调用a()的函数的名称?
进一步:
- 对不起有误导性的拼写错误。 我纠正了它。
- 我试图找出哪个函数调用a()进行调试。 在同样的情况下,我不知道你怎么做?
- 我的代码在vxWorks下,但我不确定它是否与C99或其他相关。
你只能做一件事。
但是,使用简单的标准宏技巧,您可以实现您想要的,IIUC显示调用者的名称。
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(); }
试试这个:
void a(); #ifdef DEBUG # define a( ) a_debug( , __FUNCTION__) void a_debug( , const char * calledby); #endif void b(void) { a( ); } #ifdef DEBUG # undef a #endif void a( ) { printf("'%s' called\n", __FUNCTION__); } #ifdef DEBUG void a_debug( , const char * calledby) { printf("'%s' calledby '%s'", __FUNCTION__, calledby); a( ); } #endif
例如,如果
是int i, double d, void * p
然后
是i, d, p
。
或者(更少邪恶; – >> – 但更多代码修改,因为每次调用a()都需要触及):
void a(( #ifdef DEBUG , const char * calledby #endif ); void a(( #ifdef DEBUG , const char * calledby #endif ) { #ifdef DEBUG printf("'%s' calledby '%s', __FUNCTION__, calledby); #endif ... } ... void b(void) { a( #ifdef DEBUG , __FUNC__ #endif ); }
__FUNCTION__
在GCC上可用(至少?),如果使用不同的C99编译器将其替换为__func__
。
如果您使用的是Linux系统,则可以使用backtrace()
函数。
有关更多详细信息和代码示例,请参见手册页 。
如果您的平台是Windows,您可以使用它: 走在callstack上
如果您只是在知道了用于记录/调试目的的位置之后,您可以使用宏来避免__func__
给出日志/调试函数的名称,但是调用它的函数。
处于宏中不会导致对__func__
的更改,但会“感觉”像使用函数一样。
例如
#define LOG(s, data...) log("%s: "s, __function__, ## data)
参考: https : //www.gnu.org/software/libc/manual/html_node/Backtraces.html
回溯是线程中当前活动的函数调用的列表。 检查程序回溯的常用方法是使用外部调试器,例如gdb。 然而,有时从程序内以编程方式获得回溯是有用的,例如,为了记录或诊断的目的。
头文件execinfo.h声明了三个获取和操作当前线程回溯的函数。
你可以使用gcc内置它。
void * __builtin_return_address(int level)
以下方法应该打印函数a()的直接调用者。
例:
a() { printf ("Caller name: %pS\n", __builtin_return_address(0)); }
您可以使用整数标识符标记调用a()的每个函数,该标识符作为参数传递给() ,然后在()中使用switch-case结构来告诉哪个函数调用了一个() .A printf()如果你使用它作为()中 switch-case结构的参数,将告诉哪个函数调用a()取决于整数标识符值
#include void a(int); void b(); void c(); void d(); int main(void) { b(); c(); d(); } void b() { int x=1; a(x); } void c() { int x=2; a(x); } void d() { int x=3; a(x); } void a(int x) { switch(x) { case 1: printf("b called me\n"); break; case 2: printf("c called me\n"); break; case 3: printf("d called me\n"); } }
#include #include
#define FUNCTION_NAME( FUNCTION )printf(“ FUNCTION =%s \ r \ n”,# FUNCTION );
int a() { printf("A function call"); } int b() { printf("B function call"); } int main(){ FUNCTION_NAME(a); FUNCTION_NAME(b); return 0;
}