如何绘制函数名和行号在C语言的内存地址? [英] How to map a function name and line number by a memory address in C language?

查看:157
本文介绍了如何绘制函数名和行号在C语言的内存地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你怎么能映射回函数名和行号,在GCC一个内存地址?

how can you map back function name and line number with a memory address in GCC ?

即假设在C语言中的原型:

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 );
}

那么,有没有通过GCC或任何提供的任何现有的API,能够满足我的要求?

So is there any existing APIs provided by GCC or whatever , that can meet my requirements ?

有关任何你非常感谢响应;-P

Many thanks for any of you response ;-P

推荐答案

如果您包括头

#include <execinfo.h>

,那么你可以使用 回溯()功能,以确定呼叫线路的地址, backtrace_symbols () 检索的功能的名称。但是,这不会给你的行号(尽管它可能提供足够的信息,以帮助调试,如果这是您所需要的)。

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:


  • 确保你的程序(和它的所有库)与调试启用( -g 标志GCC)编译

  • 使用 addr2line 程序到地址(从回溯())转换成文件/行号引用。可以使用系统从程序中调用这个(),例如。它会发送输出到标准输出,但可以使用重定向或管道捕获输出如果需要的话。

  • 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.

这篇关于如何绘制函数名和行号在C语言的内存地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆