简体   繁体   English

如何用C语言的内存地址映射功能名称和行​​号?

[英]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: 如果您确实需要线号,则需要:

  • Ensure that your program (and all its libraries) are compiled with debugging enabled ( -g flag to gcc) 确保在启用调试的情况下编译您的程序(及其所有库)(- -g gcc标志)
  • Use the 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. 它将把输出发送到stdout,但是如果需要,您可以使用重定向或管道来捕获输出。

使用gcc,您可以使用回溯功能来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM