简体   繁体   中英

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 ?

ie 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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