我是靠谱客的博主 朴素棉花糖,最近开发中收集的这篇文章主要介绍get caller function name in called function at runtime,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

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

/* 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]

参考

http://gcc.gnu.org/onlinedocs/gcc/Return-Address.html

或见:https://blog.csdn.net/Rong_Toa/article/details/106292394

最后

以上就是朴素棉花糖为你收集整理的get caller function name in called function at runtime的全部内容,希望文章能够帮你解决get caller function name in called function at runtime所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部