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 ?
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开发者_Go百科 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 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.
With gcc you can do this using backtrace functionality.
精彩评论