Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the name, or file and line of caller method? [duplicate]

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__ )
};
like image 702
Daniel A.A. Pelsmaeker Avatar asked Apr 08 '13 16:04

Daniel A.A. Pelsmaeker


2 Answers

Wrap DoSomething in a macro:

void DoSomethingImp(char const *, char const *file, char const *line)
{
    // do whatever needed, use file and line to report problems
}

#define DoSomething(x) DoSomethingImp(x, __FILE__, __LINE__)

DISCLAIMER:

This is not the best thing to do, people are screaming on WIN API macros defined this way for either ANSI or UNICODE. But I believe this is the only way if you don't want to change every call to DoSomething.

like image 151
Tomek Avatar answered Oct 23 '22 09:10

Tomek


To the best of my knowledge, the only way to AUTOMATICALLY get information about previous calls is to use a backtrace. This post has a ton of information about doing that:

How to generate a stacktrace when my gcc C++ app crashes

like image 20
krowe Avatar answered Oct 23 '22 08:10

krowe