Cross-platform defining #define for macros __FUNCTION__ and __func__

Viewed 26466

Compiling with gcc 4.4.2 and WinXP Visual Studio C++ 2008

#if defined ( WIN32 )
#define __FUNCTION__ __func__
#endif

As I want to use the macro to display the function name. I have done the above so I can cross-platform, and use the same func when compiling on linux or windows.

However, when I am compiling on WinXP I get the following error:

__func__ undeclared identifier

Can I not #define a macro like this?

Many thanks for any suggestions,

4 Answers

It looks like you have your #define backward. If you want to use __func__ on both platforms, and WIN32 has __FUNCTION__ but not __func__, you need to do this instead:

#if defined ( WIN32 )
#define __func__ __FUNCTION__
#endif

There may be a better way to know whether you need to define __func__ or not, but this quick hack should do the trick.

Remember, on compilers that support the __FUNCTION__ and __func__ keywords, they're not macros so you can't do the following (since #ifndef __func__ isn't valid):

#ifndef __func__
#define __func__ __FUNCTION__
#endif

From the C99 spec:

6.4.2.2 Predefined identifiers

1 The identifier __func__ shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration

static const char __func__[] = "function-name";

appeared, where function-name is the name of the lexically-enclosing function.

The __FUNCTION__ macro is pre-defined in the MSVC compiler. You'll need to make it look like this:

#ifndef _MSC_VER
#define __FUNCTION__ __func__
#endif

Or the other way around, if you prefer:

#ifdef _MSC_VER
#define __func__ __FUNCTION__
#endif

You should be able to use __func__ without any explicit macros in any compiler that supports C99.

You can of course #define such a macro. Every instance of FUNCTION is then replaced by __func__. However, obviosuly your compiler doesn't know __func__. I believe VC knows __FUNCTION__, so

#if defined ( WIN32 )
#  define __func__ __FUNCTION__
#endif

might do.

Related