views:

89

answers:

1

Hi, I want to know how to find out if the preprocessor macro __PRETTY_FUNCTION__ can be used with a given compiler (As it is supposed to be non-standard). How do I check this in a header file? What I want to do is something like:

#ifndef __PRETTY_FUNCTION__
   #define __PRETTY_FUNCTION__ __func__
#endif

But, I'm guessing what happens is the preprocessor defines the macro in place for each function so I wonder whether there's any meaning to __PRETTY_FUNCTION__ (Unlike __FILE__ or __LINE__) outside a function. Is this true or can I just use the code above? If not, how do I check for it?

EDIT: I tried it. __PRETTY_FUNCTION__ is undefined outside a function (I didn't check inside a class). So there has to be another way.

EDIT2: Actually a simple hack would be to do this :):

void Dummy()
{
    #ifndef __PRETTY_FUNCTION__
       #define __PRETTY_FUNCTION__ __func__
    #endif
}

The other method is to check for compiler as was suggested by others.

+3  A: 

You probably have to know which compiler you're using. For GCC (the GNU Compiler Collection), you'd probably test:

#ifdef __GNUG__
...use __PRETTY_FUNCTION__
#endif

You might check the compiler version if you know which one introduced the feature and you are in any danger of having your code compiled with an older version.

The GCC (4.4.1) manual says:

In C, __PRETTY_FUNCTION__ is yet another name for __func__. However, in C++, __PRETTY_FUNCTION__ contains the type signature of the function as well as its bare name. For example, this program:

 extern "C" {
     extern int printf (char *, ...);
 }
 class a {
 public:
     void sub (int i)
     {
         printf ("__FUNCTION__ = %s\n", __FUNCTION__);
         printf ("__PRETTY_FUNCTION__ = %s\n", __PRETTY_FUNCTION__);
     }
 };
 int
 main (void)
 {
     a ax;
     ax.sub (0);
     return 0;
 }

gives this output:

 __FUNCTION__ = sub
 __PRETTY_FUNCTION__ = void a::sub(int)

These identifiers are not preprocessor macros. In GCC 3.3 and earlier, in C only, __FUNCTION__ and __PRETTY_FUNCTION__ were treated as string literals; they could be used to initialize char arrays, and they could be concatenated with other string literals. GCC 3.4 and later treat them as variables, like __func__. In C++, __FUNCTION__ and __PRETTY_ FUNCTION__ have always been variables.

Jonathan Leffler