我怎么知道哪个函数或文件,哪一行调用了一个函数

How can I know which function or file and which line called a function?

本文关键字:函数 一行 一个 调用 文件 我怎么知道      更新时间:2023-10-16

例如

void MyFunction()
{
    printf( "This function is called by %s in file %s on line $i.n", func, file, line ); // Where func, file and lines should be replaced
}
int main()
{
    MyFunction();
    return 0;
}

在Linux上,您可以使用backtrace来转储堆栈:

   backtrace() returns a backtrace for the calling program, in the array
   pointed to by buffer.  A backtrace is the series of currently active
   function calls for the program.  Each item in the array pointed to by
   buffer is of type void *, and is the return address from the
   corresponding stack frame.  The size argument specifies the maximum
   number of addresses that can be stored in buffer.  If the backtrace
   is larger than size, then the addresses corresponding to the size
   most recent function calls are returned; to obtain the complete
   backtrace, make sure that buffer and size are large enough.