C语言中如何通过内存地址映射函数名和行号?
如何用 GCC 中的内存地址映射函数名称和行号?
即假设一个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 );
}
那么GCC或其他提供的现有API是否可以满足我的要求?
非常感谢你们的回复;-P
how can you map back function name and line number with a memory address in GCC ?
i.e assuming a prototype in C language:
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 ?
Many thanks for any of you response ;-P
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果包含标头
,则可以使用
backtrace()
函数 确定调用行的地址,以及backtrace_symbols()
< /a> 检索函数的名称。但是,这不会为您提供行号(尽管它可能会提供足够的信息来帮助调试,如果这是您需要的)。如果您确实需要行号,那么您需要:
-g
标志)addr2line
程序 用于转换地址(从backtrace()) 到文件/行号引用中。例如,您可以使用
system()
从程序中调用它。它将输出发送到 stdout,但如果需要,您可以使用重定向或管道来捕获输出。If you include the header
then you can use the
backtrace()
function to determine the address of the calling line, andbacktrace_symbols()
to retrieve the names of the functions. 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)addr2line
program to translate addresses (retrieved frombacktrace()
) into file/line number references. You can call this from your program usingsystem()
, for example. It will send the output to stdout, but you can use redirection or a pipe to capture the output if required.通过 gcc,您可以使用 backtrace 功能来完成此操作。
With gcc you can do this using backtrace functionality.