如何在 C 中为 __func__ 赋值?

How to assign value to __func__ in C?

出于某种原因,我没有在文档中的任何地方找到这个问题的直接答案。

我的朋友说我可以直接使用__func__并赋值给它,而不用实际声明它。

documentation 说:

1. The identifier __func__ shall be implicitly declared by the translator as
if, immediately following the opening brace of each function definition, the
declaration

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

appeared, where function-name is the name of the lexically-enclosing function.

那么,这是否意味着,我应该在每次以 static const char __func__[] = "function-name"; 而不是 strcpy(__func__, "function-name"); 开始函数时声明它,因为它已经被声明并将由编译器处理?

如果这听起来像是一个基本问题,我很抱歉,但我很困惑!

您不需要声明或定义它。它在函数定义中对您的代码隐式可用。

void func_with_fancy_name() 
{
  puts(__func__); // Will print the function name
}

分配是另一回事。你不能这样做。 "as if" 声明中的 const 说明符应该会阻止你。

My friend says I can directly use __func__ [...]

是的,你可以。注意这部分

[...] shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration

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

appeared, [...]

所以,你不需要很明确。

.. and assign to it,

不,你不能。它是一个常数。