49

__FILE__ and __LINE__ are well known. There is a __func__ since C99.

#include <iostream>
struct Foo {
        void Do(){ std::cout << __func__ << std::endl; }
};

int main()
{
        std::cout << __func__ << std::endl;
        Foo foo; foo.Do();
        return 0;
}

will output

main
Do

Is there any macro / keyword that would output method name like Foo::Do?

Notinlist
  • 16,144
  • 10
  • 57
  • 99

6 Answers6

93

Boost has a special utility macro called BOOST_CURRENT_FUNCTION that hides the differences between the compiler implementations.

Following it's implementation we see that there are several macros depending on compiler:

  • __PRETTY_FUNCTION__ -- GCC, MetroWerks, Digital Mars, ICC, MinGW
  • __FUNCSIG__ -- MSVC
  • __FUNCTION__ -- Intel and IBM
  • __FUNC__ -- Borland
  • __func__ -- ANSI C99
Narek
  • 38,779
  • 79
  • 233
  • 389
Kornel Kisielewicz
  • 55,802
  • 15
  • 111
  • 149
10
  • On GCC you can use __FUNCTION__ and __PRETTY_FUNCTION__.
  • On MSVC you can use __FUNCSIG__ and __FUNCTION__.
rpg
  • 7,746
  • 3
  • 38
  • 43
3

There's no such macro in standard C++, and that includes the draft C++0x standard I looked at. It would complicate compilation, since parsing (necessary to determine what a function is) comes after preprocessing, and I suspect that's why there's nothing in the standard.

The __func__ you're using is nonstandard, although it apparently works on your compiler.

David Thornley
  • 56,304
  • 9
  • 91
  • 158
  • This is of course nonsense as it can insert an implementation defined runtime function. Preprocessor String concatanation would then impossible but it's not allowed for other preprocessor symbols either. – Lothar Jan 18 '15 at 02:41
1

Not in Standard C++ (and __func__ is not part of C++). Your implementation may have such a feature though - which compiler are you using?

1

See "Predefined Macros (C/C++)" for a complete list supported by MS Visual Studio.

Ruddy
  • 1,734
  • 10
  • 11
  • 3
    That document lives here, now: https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros – adam_0 Feb 14 '18 at 22:03
0

This might be useful:

http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html

#include"stdio.h"
#include"stdlib.h"
int main()
{
printf("line number is %d .. func name is %s, file name is %s",__LINE__,__PRETTY_FUNCTION__,__FILE__);
return  0;
}

This is how to print line number, function name and file name in gcc.

Mayank
  • 2,150
  • 1
  • 15
  • 13