(转)get caller function name in called function at runtime

如题,想搞个这功能,增强failmalloc,不知道能否解决问题,有时间搞下,后续会跟进报道进展~—_—~

http://www.quora.com/C-programming-language/Is-there-a-way-to-print-the-name-of-the-calling-function-in-C-without-passing-it-as-an-argument

Although it's not very efficient and will affect your program's timing, one way is to compile your program with its symbol table (gcc -g ...), call the gcc function __builtin_return_address() as described by Kalyan and then call addr2line externally to decode it.  Alternatively, you could probably incorporate the functionality of addr2line directly into your program to provide this natively.

Example:

gcc -g -o print_caller print_caller.c
./print_caller 
f1
print_caller.c:28

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* print_caller.c */
 
#include <stdio.h>
 
void
print_function(void *p) {
    char cmd[128];
    FILE *fp;
 
    snprintf(cmd, sizeof(cmd), "addr2line -e %s -f %p", "print_caller", p);
    fp = popen(cmd, "r");
    if (fp) {
        char buf[128];
        while (fgets(buf, sizeof(buf), fp)) {
            printf("%s", buf); 
        }
    }
}
 
void
f2(void) {
    print_function(__builtin_return_address(0));
}
 
void
f1(void) {
    f2();
}
 
int
main(int argc, char *argv[]) {
    f1();
    return(0);
}

As far as I think I know, I don't think there is a macro like __FUNCTI qrablurexp ON__ to directly print the caller function.

However, there are some GCC extensions to print the return address of the current function, caller function etc to some levels. So, from the returned 'return address' with a 'level' of 1, you should be able to find out the caller.

Refer to:
void * __builtin_return_address( unsigned int level ); [1]



References:
1. http://gcc.gnu.org/onlinedocs/gc...

转载于:https://www.cnblogs.com/europelee/archive/2012/08/08/2629177.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值