Search code examples
cruntimedebug-symbols

Is there a way to access debug symbols at run time?


Here's some example code to give an idea of what I want.

int regular_function(void)
{
     int x,y,z;
     /** do some stuff **/
     my_api_call();
     return x;
}
...
void my_api_call(void)
{
    char* caller = get_caller_file();
    int line = get_caller_line();
    printf("I was called from %s:%d\n", caller, line);
}

Is there a way to implement the get_caller_file() and get_caller_line()? I've seen/used tricks like #defineing my_api_call as a function call passing in the __FILE__ and __LINE__ macros. I was wondering if there was a way to access that information (assuming it's present) at run time instead of compile time? Wouldn't something like Valgrind have to do something like this in order to get the information it returns?


Solution

  • If you have compiled your binary with debug symbols, you may access it using special libraries, like libdwarf for DWARF debug format.