1

Objective:

I want my class method to retrieve the caller function signature. In the same way __PRETTY_FUNCTION__ does for a local function.

Below you encounter a sample code and the output. I want the output 2 to be like 3.

Restriction: MyClass::foo can't be static. Otherwise, it would be enough to create a macro like

#define foo() MyClass::foo(__PRETTY_FUNCTION__)

after the class declaration and we would have our solution.

#include <iostream>

class MyClass {
public:
    void foo(const char* parent = __builtin_FUNCTION()) {
        std::cout << "1: " << __PRETTY_FUNCTION__ << std::endl;
        std::cout << "2: " << parent << std::endl;
    }
};

namespace Space
{
    void bar(int notUsedParam){
        MyClass myClass;
        myClass.foo();
        std::cout << "3: " << __PRETTY_FUNCTION__ << std::endl;
    }
}

int main() {
    Space::bar(1);
    return 0;
}

Output:

1: void MyClass::foo(const char*)
2: bar
3: void Space::bar(int)

Some Reference: https://clang.llvm.org/docs/LanguageExtensions.html#source-location-builtins

Oshio
  • 133
  • 4
  • 17
  • What outcome do you want, and why doesn't your macro solution work (`myclass.MyClass::foo(__PRETTY_FUNCTION__)`)? Have you tried a default argument of [`std::source_location::current()`](https://en.cppreference.com/w/cpp/utility/source_location/current)? – user3188445 Jul 02 '22 at 04:47
  • clang implementation of std::source_location has some issues with my IDE. Explanation: https://stackoverflow.com/questions/67707251/c20-in-qt-creator. But yes is a valid – Oshio Jul 02 '22 at 05:45
  • I am developing under windows, so I also tried compiling with MinGW. But it only supports the std::experimental::source_location::current(). This implementation only returns the caller function name. – Oshio Jul 02 '22 at 05:48
  • But according to the documentation that you linked, it should work if I try to compile with GCC under Linux. So I will try to compile it under my Arch later. – Oshio Jul 02 '22 at 05:51
  • You can see what I am talking about std::experimental::source_location::current() here is the example: https://onlinegdb.com/dp4lwvkqE – Oshio Jul 02 '22 at 05:54
  • @Oshio Does this help? https://stackoverflow.com/questions/4636456/how-to-get-a-stack-trace-for-c-using-gcc-with-line-number-information It allows you to get full stack trace. – lorro Jul 02 '22 at 21:02

0 Answers0