如何查找此预处理宏是否存在?

4

我想知道如何判断特定编译器是否支持预处理器宏__PRETTY_FUNCTION__(因为该宏是非标准的)。我应该如何在头文件中检查这个呢?我的目的是这样的:

#ifndef __PRETTY_FUNCTION__
   #define __PRETTY_FUNCTION__ __func__
#endif

但是,我猜想预处理器会为每个函数定义宏,所以我想知道在函数外部是否有任何意义使用__PRETTY_FUNCTION__(不像__FILE____LINE__)。这是真的吗?如果不是,我该如何检查呢?

编辑:我尝试了一下。在函数外部,__PRETTY_FUNCTION__未定义(我没有在类内部检查)。因此必须有另一种方法。

编辑2:实际上,一个简单的hack方法是这样做:)

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

另一种方法是检查编译器,正如其他人建议的那样。

抱歉,但是您的问题不是很清楚...我想知道如何找出预处理器宏__PRETTY_FUNCTION__是否可以与给定的编译器一起使用,并且任何有效命名的预处理器宏都可以在任何编译器上使用。您的意思是询问它是否内置并默认定义为给定编译器吗?如果是这样,那么您可以使用#IFDEF。我真的不明白您所说的“预处理器为每个函数定义了该宏”的含义-您能否重新表述一下,我们可以尝试帮助您。 - Mawg says reinstate Monica
1个回答

4
您可能需要知道正在使用哪个编译器。对于GCC(GNU编译器集合),您可以尝试测试以下内容:
#ifdef __GNUG__
...use __PRETTY_FUNCTION__
#endif

如果你知道哪个编译器版本引入了这个功能,并且你的代码有可能被旧版本编译,那么你可以检查编译器版本。

GCC(4.4.1)手册如下:

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.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接