How do I get the name of the calling function?

后端 未结 3 512
广开言路
广开言路 2021-02-04 03:38

I am using gnu tool chain. How can I, at run time, find caller of a function? i.e for example function B() gets called by many functions using function pointers. Now, whenever B

3条回答
  •  孤街浪徒
    2021-02-04 04:35

    Another method, pointed out by Vasil Dimov in answer to a similar question, is to replace the function call with a wrapper macro that reports or passes in the calling function name. This will work with inline functions, where backtrace won't. On the other hand it won't work if you call the function by reference, or otherwise take its address.

    For example this:

    int B(int x){
        ...
    }
    

    could become:

    int _B(int x, char *caller){
        printf("caller is %s\n", caller);
        ...
    }
    
    #define B(x) _B((x), __func__)
    

    and every call to B() will print the callers name. Vasil Dimov constructs it differently, printing the name directly in the macro and leaving the function unchanged.

提交回复
热议问题