[英]How to map a function name and line number by a memory address in C language?
how can you map back function name and line number with a memory address in GCC ? 如何在GCC中将函数名称和行号与内存地址映射起来?
ie assuming a prototype in C language: 即假设使用C语言编写原型:
void func() {
// Get the address of caller , maybe this could be avoided
MemoryAddress = get_call_address();
// Which line from source code is executing , which calls func()
LineNumber = get_lineno_from_symbol ( &MemoryAddress );
// Grab the name who calls func()
FunctionName = get_func_from_symbol ( &MemoryAddress );
}
So is there any existing APIs provided by GCC or whatever , that can meet my requirements ? 那么,是否有GCC提供的任何现有API可以满足我的要求?
Many thanks for any of you response ;-P 非常感谢您的任何答复;-P
If you include the header 如果包含标题
#include <execinfo.h>
then you can use the backtrace()
function to determine the address of the calling line, and backtrace_symbols()
to retrieve the names of the functions. 那么您可以使用
backtrace()
函数确定调用行的地址,并使用backtrace_symbols()
检索函数的名称。 However, this will not give you the line numbers (though it may give enough information to help with debugging, if this is what you require). 但是,这不会给您行号(尽管如果您需要的话,它可能会提供足够的信息来帮助调试)。
If you absolutely do need line numbers, then you'll need to: 如果您确实需要线号,则需要:
-g
flag to gcc) -g
gcc标志) addr2line
program to translate addresses (retrieved from backtrace()
) into file/line number references. addr2line
程序将地址(从backtrace()
检索)转换为文件/行号引用。 You can call this from your program using system()
, for example. system()
从程序中调用它。 It will send the output to stdout, but you can use redirection or a pipe to capture the output if required. 使用gcc,您可以使用回溯功能来做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.