How can we know the caller function's name?

后端 未结 10 1551
北海茫月
北海茫月 2020-12-02 10:26

In the C language, __FUNCTION__ can be used to get the current function\'s name. But if I define a function named a() and it is called

相关标签:
10条回答
  • 2020-12-02 11:18

    You can do it with a gcc builtin.

    void * __builtin_return_address(int level)

    The following way should print the immediate caller of a function a().

    Example:

    a() {
        printf ("Caller name: %pS\n", __builtin_return_address(0));
    }
    
    0 讨论(0)
  • 2020-12-02 11:21

    Refer: https://www.gnu.org/software/libc/manual/html_node/Backtraces.html

    A backtrace is a list of the function calls that are currently active in a thread. The usual way to inspect a backtrace of a program is to use an external debugger such as gdb. However, sometimes it is useful to obtain a backtrace programmatically from within a program, e.g., for the purposes of logging or diagnostics.

    The header file execinfo.h declares three functions that obtain and manipulate backtraces of the current thread.

    0 讨论(0)
  • 2020-12-02 11:27

    If your platform is Windows, you may use this: walking the callstack

    0 讨论(0)
  • 2020-12-02 11:27

    If you're only after knowing where you were for logging/debug purposes you can use a macro to avoid __func__ giving the name of your logging/debug function but of the function calling it.

    Being in a macro will not result in a change to __func__ but will "feel" like using a function.

    e.g.

    #define LOG(s, data...) log("%s: "s, __function__, ## data)
    
    0 讨论(0)
提交回复
热议问题