如何消除关于 __FUNCTION__ 的 GCC 迂腐 (-Wpedantic) 警告

How to silence GCC pedantic (-Wpedantic) warning regarding __FUNCTION__

我正在使用“__FUNCTION__”打印出 (printf) 输入的函数名称预定义宏(在 gcc 和 clang 中)。但是,如果我使用 -Wpedantic,我会收到此警告:

warning: ISO C does not support ‘__FUNCTION__’ predefined identifier [-Wpedantic]

如何消除该警告?

除非您尝试遵守 ANSI C 标准,否则不要使用 -Wpedantic,该标准显然不支持 __FUNCTION__ 关键字。

改用-Wall -Wextra

没有理由使用__FUNCTION__

__func__ 是标准的(C99,C11,C17)。 C11 6.4.2.2p1:

  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";
    

来自 GCC documentation:

__FUNCTION__ is another name for __func__, provided for backward compatibility with old versions of GCC.

如果您想知道几岁,__func__ 出现在 GCC 2.95 中,发布于 1999 年 7 月 31 日。请注意,您不需要 __FUNCTION__ 任何其他东西 支持 GCC 2.94 或更早版本 。如果你这样做,那么这个警告可能是你最不担心的。


但是,__func__ 在 C89/90 模式下也不可用,因此您会在那里收到警告。如果您关心 ISO 诊断,则需要使用更新的版本。现代 GCC 已经默认为 GNU C11 或 C17。


另请参阅: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__

-Wpedantic 选项用于:

发出严格的ISO C和ISO C++要求的所有警告;拒绝所有使用禁止扩展的程序,以及其他一些不遵循 ISO C 和 ISO C++ 的程序。对于 ISO C,遵循由使用的任何 -std 选项指定的 ISO C 标准版本。

__FUNCTION__ 是 GCC 扩展。但是 __func__ 是 C11 中的预定义标识符。我知道这也是 C99 的一部分。

C11 (N1570) 的委员会草案指出:

6.4.2.2 Predefined identifiers
Semantics
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.

符合标准的函数标识符是__func__

来自 C11 规范的 §6.4.2.2

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.

我相信 __func__ 是在 C99 中添加的。