1

I'm using __FUNCTION__, __PRETTY_FUNCTION__ macros in my code and learned that the code needs to compile under compilers other than GCC. Are these macros part of the standard? or GCC extension? Should I use __func__ instead?

Sampath
  • 1,144
  • 1
  • 21
  • 38
  • 1
    No these macros aren't part of the standard. – πάντα ῥεῖ Mar 13 '17 at 08:02
  • 2
    `__func__` is standardized from C++11, hence, yes, you should prefer it – Danh Mar 13 '17 at 08:03
  • 1
    FWIW, `__func__` is a const static variable, not a macro – Danh Mar 13 '17 at 08:04
  • 1
    Possible duplicate of [What's the difference between \_\_PRETTY\_FUNCTION\_\_, \_\_FUNCTION\_\_, \_\_func\_\_?](http://stackoverflow.com/questions/4384765/whats-the-difference-between-pretty-function-function-func) – Danh Mar 13 '17 at 08:05
  • 1
    I've been using `__FUNCTION__` in code since the 90's across different compilers. If it's not a *standard* as per the language lawyers, then it *practically is a standard*.... You've asked a couple of different questions on other posts about *will this macro work on other compilers*. Porting C/C++ to work across compilers has a lot of annoyances and quirks. The function, line, and file macros are the **least** of these issues that come up. :) – selbie Mar 13 '17 at 08:14
  • 1
    They are also different. So in MSVC you can do `std::cerr << “Error in “ __FUNCTION__;` because it’s a macro but in clang is doesn’t compile because it’s a static. – QuentinUK Jan 07 '23 at 10:56

2 Answers2

3
  • __FUNCTION__ is available pretty much everywhere but it is just a simple function name
  • __PRETTY_FUNCTION__ with GCC compatible compilers like GCC, Clang and Intel's compiler and even with compilers like Sun Studio 12's one.
  • beware, __func__ is not a macro
  • Visual Studio C++ compiler has __FUNCSIG__ (you probably want this) and __FUNCDNAME__ (less useful as it is the full decorated name)
wilx
  • 17,697
  • 6
  • 59
  • 114
2

Are these macros part of the standard?

No.

Should I use __func__ instead?

__func__ is standard (and is not a macro). If a compiler does not support the others, you can fall back to this - as long as the compiler supports a recent standard. On an older compiler, you'll have to use a compiler specific macro.

Note that the different macros may provide varying levels of information beyond the function name. __PRETTY_FUNCTION__ in particular provides useful additional information (namespace qualified, full signature, template arguments).

If you want the prettiest function name a compiler has to offer (if any), you need to detect the compiler with pre defined macros and research what each compiler version support. Or, if you don't like re-implementing what others have already done for you, you could use BOOST_CURRENT_FUNCTION.

eerorika
  • 232,697
  • 12
  • 197
  • 326