How to know what function called another

后端 未结 7 1620
佛祖请我去吃肉
佛祖请我去吃肉 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:26

    There isn't anything that is supported in all implementations that will do what you want. I have occasionally found myself in the same situation, where I needed to track callers for a few methods and did something like the following:

    #ifdef TRACKBACK
    int foo(int arg1, int arg2, const char * file, int line)
    {
        SEND_TO_LOG("foo", file, line);
    #else
    int foo(int arg1, int arg2)
    {
    #endif
        ...
        ...
    

    Of course, it makes for a bit of a headache at the calling end, so you'll want to do something like:

    #ifdef TRACKBACK
        #define TRACKING, __FILE__, __LINE__
    #else
        #define TRACKING
    #endif
    

    Then the call:

    foo(arg1, arg2 TRACKING);  //note the lack of the comma
    

    It does the trick when all else fails.

提交回复
热议问题