GCC __func__ 被评估为空字符串

GCC __func__ gets evaluated to an empty string

鉴于我正在处理的项目中的以下代码:

/* Pre-definitions in a pre-definitions file to be included in the project */
#ifdef  WIN32
#define __FUNCNAME__ __FUNCTION__
#else
#define __FUNCNAME__ __func__  
#endif

/* My definitions */
#define MAC() \
     MAC1()

#define MAC1() \
     myPrintFunction(__FUNCNAME__)

/* My print function */
void myPrintFunction(const char * functionName)
{
     printf("\n func name: %s \n",functionName);
}

/* Macro usage example function */
void myFunction()
{
     if (some_condition)
     {
         MAC();
     }
}

函数名称显示为空字符串。 知道为什么,我该如何解决?

代码在 Linux 机器上编译和测试,使用 GCC 编译器。

开箱即用 __func__。自 C99 以来,它一直是 C 标准的一部分。更改您的编译器设置以至少使用该标准。

请注意 __func__ 不是 宏,而是 预定义标识符 一个函数体完全等同于在那个时候使用它,先写

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

就在函数体的左大括号之后。

您当前代码的正式行为是未定义。系统保留任何包含两个连续下划线的符号。 (包括宏名称、函数名称和变量名称。)

您提供的代码给出了预期的结果(一旦我添加了必要的包含和主要内容):

#include <stdio.h>

#ifdef  WIN32
#define __FUNCNAME__ __FUNCTION__
#else
#define __FUNCNAME__ __func__  
#endif

/* My definitions */
#define MAC() \
     MAC1()

#define MAC1() \
     myPrintFunction(__FUNCNAME__)

void myPrintFunction(const char * functionName)
{
     printf("\n func name: %s \n",functionName);
}

int main()
{
    MAC();
}

我使用 gcc -std=c11 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds 编译了这个,没有任何警告。

您真的应该 post 一个实际编译的完整(但最小)示例,以及您使用的编译器标志,因为肯定有一些不同的东西来解释您描述的症状。

此外,在将语句编写为宏时,您可能会发现使用 do {...} while (0) 习惯用法有助于避免意外扩展更改控制流。