views:

57

answers:

3

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?

+1  A: 

This is highly environment-specific. In most Windows and Linux implementations where debug symbols are provided, the tool vendor provides or documents a way of doing that. For a better answer, provide implementation specifics.

wallyk
I was thinking generally, but would probably only ever do it on Linux.
jdizzle
+4  A: 

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

qrdl
+1. If I didn't see it, this was half what I'd answer. The other half is for Windows executables you'd want to look into using DbgHelp.lib (aka DebugHelp). See http://msdn.microsoft.com/en-us/library/ms679309(VS.85).aspx
T.E.D.
A: 

Debugging symbols, if available, need to be stored somewhere so the debugger can get at them. They may or may not be stored in the executable file itself.

You may or may not know the executable file name (argv[0] is not required to have the full path of the program name, or indeed have any useful information in it - see here for details).

Even if you could locate the debugging symbols, you would have to decode them to try and figure out where you were called from.

And your code may be optimised to the point where the information is useless.

That's the long answer. The short answer is that you should probably rely on passing in __FILE__ and __LINE__ as you have been. It's far more portable an reliable.

paxdiablo