How to know what function called another

后端 未结 7 1684
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-11 17:53

I wanna know if there is any way to know where the function currently in execution was called, this is, in what file and line. I\'m using C language, and I\'m looking for so

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-11 18:24

    __FILE__, __LINE__ etc are preprocessor macros which can easily be expanded to the correct value at compile time. A function may get called from many possible places, so that can't be done via the preprocessor. Finding out the caller's name would be very difficult; it involves walking the stack and matching addresses to symbols.

    If you can live with a small hack, this might work (untested):

    /* Add a called argument to your function */
    void _myFunction(char *caller, int more_args)
    
    /* And define a macro that adds it automagically */
    #define myFunction(a) _myFunction(__FUNCTION__, a)
    

提交回复
热议问题