为什么 C++ 不推荐使用的警告会打印两次?

duc*_*ayr 5 c++ gcc g++

如果我有

namespace foo {
    inline int bar() {
        return 1119;
    }
}

__attribute__((deprecated)) inline int bar() {
    return 138;
}
Run Code Online (Sandbox Code Playgroud)

header.h

#include "header.h"
#include <iostream>

int main() {
    int x = bar();
    int y = foo::bar();
    std::cout << x << std::endl;
    std::cout << y << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

source.cpp,那么

g++ source.cpp -o deprecated-test
Run Code Online (Sandbox Code Playgroud)

结果是

source.cpp: In function ‘int main()’:
source.cpp:5:17: warning: ‘int bar()’ is deprecated [-Wdeprecated-declarations]
     int x = bar();
                 ^
In file included from source.cpp:1:
header.h:7:40: note: declared here
 __attribute__((deprecated)) int bar() {
                                 ^~~
source.cpp:5:17: warning: ‘int bar()’ is deprecated [-Wdeprecated-declarations]
     int x = bar();
                 ^
In file included from source.cpp:1:
header.h:7:40: note: declared here
 __attribute__((deprecated)) int bar() {
Run Code Online (Sandbox Code Playgroud)

(在带有 g++ 8.2.0 的 Ubuntu 18.10 上)。

为什么不推荐使用的警告会打印两次?

排除一些无益的建议:

  • [[deprecated]]:我知道在 C++14 上可以使用该[[deprecated]]属性,但我需要使用 C++11。

  • 声明与定义:文档似乎暗示它应该与函数声明而不是定义一起使用,但是

    1. 我需要定义函数 inline在头文件中,而不是在头文件中声明并在源文件中定义;和
    2. 无论如何,尝试这种方法并没有阻止警告打印两次。

P.W*_*P.W 1

根据 GCC 8.2.0 的文档:

如果在源文件中的任何位置使用该函数,则不推荐使用的属性会导致警告。当识别预计在程序的未来版本中删除的功能时,这非常有用。该警告还包括已弃用函数的声明位置,以便用户能够轻松找到有关该函数为何被弃用或他们应该做什么的更多信息。请注意,警告仅在使用时出现...

应该只有一个警告而不是两个。所以这是 GCC 中的一个错误。

类型属性(而不是函数属性)有一个相关的错误,标题为: C/C++__attribute__((deprecated))似乎没有按照文档隐含的方式包装声明。

它已被确认为一个错误。