为什么#ifndef __func__返回true?

时间:2017-12-13 22:35:18

标签: c++ func

以下代码,

WSGIApplicationGroup %{GLOBAL}
WSGIRestrictEmbedded On

<VirtualHost *:80>
ServerName example.com
WSGIDaemonProcess myprocess threads=10 home=/home/ubuntu/myapp
WSGIProcessGroup myprocess
...
</VirtualHost>

<VirtualHost *:443>
ServerName example.com
WSGIProcessGroup myprocess
...
</VirtualHost>

给出以下预期输出

#include <iostream>

#ifndef __func__
#   ifdef __FUNCTION__
#       define __func__ __FUNCTION__
#   else
//#       error This compiler supports neither __func__ nor __FUNCTION__
#   endif
#endif


int main(int argc, char **argv)
{
    std::cout << __func__ << std::endl
              << __FUNCTION__ << std::endl
              << __PRETTY_FUNCTION__ << std::endl;
}

但是,如果我取消注释main main int main(int, char**) 条件,则编译失败,因为else__func__都未定义。怎么会这样?它们显然定义为上面的输出中所示。关于我__FUNCTION__ / #ifdef我是否缺少一些简单的原则?

1 个答案:

答案 0 :(得分:3)

__func__不是宏。它是一个神奇的变量,__FUNCTION____PRETTY_FUNCTION__

来自https://gcc.gnu.org/onlinedocs/gcc-4.9.0/gcc/Function-Names.html

  

GCC提供三个魔术变量,用于保存当前函数的名称,作为字符串。第一个是__func__,它是C99标准的一部分:

     

标识符__func__由翻译者隐式声明,就像紧跟在每个函数定义的左括号之后的声明一样

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

...

     

__FUNCTION____func__的另一个名称。

     

...

     

在C中,__PRETTY_FUNCTION____func__的另一个名称。但是,在C ++中,__PRETTY_FUNCTION__包含函数的类型签名及其裸名称。