C语言中如何通过内存地址映射函数名和行号?

发布于 2024-10-17 02:34:11 字数 479 浏览 1 评论 0原文

如何用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

知你几分 2024-10-24 02:34:12

如果包含标头

#include <execinfo.h>

,则可以使用 backtrace() 函数 确定调用行的地址,以及 backtrace_symbols()< /a> 检索函数的名称。但是,这不会为您提供行号(尽管它可能会提供足够的信息来帮助调试,如果这是您需要的)。

如果您确实需要行号,那么您需要:

  • 确保您的程序(及其所有库)是在启用调试的情况下编译的(gcc 的 -g 标志)
  • 使用 addr2line 程序 用于转换地址(从 backtrace()) 到文件/行号引用中。例如,您可以使用 system() 从程序中调用它。它将输出发送到 stdout,但如果需要,您可以使用重定向或管道来捕获输出。

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. 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)
  • Use the addr2line program to translate addresses (retrieved from backtrace()) into file/line number references. You can call this from your program using system(), for example. It will send the output to stdout, but you can use redirection or a pipe to capture the output if required.
风向决定发型 2024-10-24 02:34:12

通过 gcc,您可以使用 backtrace 功能来完成此操作。

With gcc you can do this using backtrace functionality.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文