Is there a way in C++11 (using the latest GCC) to get the name, or the file and line number, of the method calling the currently executed method (the caller)?
I want to use this information in an error message when, for example, the following code fails:
void SomewhereInMyProgram()
{
DoSomething(nullptr);
}
void DoSomething(const char* str)
{
Contract::Requires(str != nullptr);
// ...
}
Currently I have code in place that reports the error as occurring in DoSomething
. While this is technically true, I'd like it to report the error as occurring in SomewhereInMyProgram
wherever that may be. That would make my life a whole lot easier!
The solution can use any C++11 features, macro's or GCC specific stuff, but rather not something I have to add at each and every call site.
I think a stacktrace will not help me, because I cannot use exception handling. Actually, I'm very limited: it's a freestanding environment where the standard C++ headers are not available. I was hoping for a macro solution of some sort.
class Contract
{
public:
static void RequiresImpl(bool condition, const char* expression,
const char* file, int line);
#define Requires(condition) RequiresImpl(condition, #condition , \
__FILE__, __LINE__ )
};