caller function name, its filename and line number
Vicente Benjumea
vicente@lcc.uma.es
Fri Jun 27 16:42:00 GMT 2003
/*
* Hello, does anyone know how can a function to know what is the
* function name of its caller, and in which file and from what
* line number the call was done ???
* It is supossed that it is done in a transparent way, that is, the
caller
* does not have to do any special action.
* I mean by using the debugging information stored in the object file,
* and using GCC as the compiler/linker. The target machine should be
* an Intel ix86 and the host system GNU/Linux and Windows
*
* Its purpose is to improve some error diagnose messages from a library
*
* Thank you very much in advance
* Vicente
*/
//- main.cpp ------------------------------------------------------------------
#include <iostream>
#include <string>
using namespace std;
#ifdef __GNUC__
void
look_for_caller_file_and_line(const void* return_addr, const void*
frame_addr,
string& caller_name, string& filename, int&
line)
{
/*
* It should look for the caller function name and the file name
* and line number where the call was done.
*
* It could be done through the frame pointer, the stack and
* the symbol table or whatever other means.
*
* It should be possible to do it, because gdb is able to do it under
* the backtrace command (or up command)
*/
}
#endif
void
check(int x)
{
if (x > 10) {
#ifdef __GNUC__
string caller_name;
string filename;
int line;
const void* return_addr = __builtin_return_address(0);
const void* frame_addr = __builtin_frame_address(0);
look_for_caller_file_and_line(return_addr, frame_addr,
caller_name, filename, line);
cout << "Error: value out of range " << x
<< " in " << caller_name
<< " in " << filename
<< " at line " << line << endl;
#else
cout << "Error: value out of range " << x << endl;
#endif
abort();
}
}
int
main()
{
check(5); // this is file main.cpp at line 65
check(20); // this is file main.cpp at line 66
}
//- main.cpp ------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Desired output:
//
// Error: value out of range 20 in main in main.cpp at line 66
//-----------------------------------------------------------------------------
More information about the Gcc-help
mailing list