Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-platform defining #define for macros __FUNCTION__ and __func__

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,

like image 526
ant2009 Avatar asked Feb 17 '10 15:02

ant2009


2 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.

like image 65
tomlogic Avatar answered Oct 29 '22 03:10

tomlogic


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
like image 34
Hans Passant Avatar answered Oct 29 '22 03:10

Hans Passant