为什么#ifndef __func__返回true

Why does #ifndef __func__ return true?

本文关键字:true 返回 func 为什么 #ifndef      更新时间:2023-10-16

以下代码,

#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/#ifndef,我在这里缺少一些简单的原则吗?

__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__包含该功能的类型签名以及其裸机。