为什么-I编译器选项会导致不同的警告触发?

问题描述 投票:1回答:1

最近,我被委以重构一个应用程序的任务,遇到了一个相当奇怪的问题。我已经尽可能地将这个问题简化为示例代码。请考虑以下内容。

offender.h

__attribute__ ((visibility ("default")))
typedef struct A {
    int a;
} A;

test.cpp。

#include <iostream>

#include <offender.h>

int main(void)
{
    A a;
    a.a = 10;
    std::cout << a.a << "\n";
    return 0;
}

如果我运行:

g++ -Wall -Werror -o test -I. test.cpp
In file included from test.cpp:3:
./offender.h:4:3: error: ‘visibility’ attribute ignored [-Werror=attributes]
    4 | } A;
      |   ^
cc1plus: all warnings being treated as errors
make: *** [Makefile:3: all] Error 1

这是有道理的,但是,如果我把 offender.h 移到一个系统定义的路径中,并且编译时不加 -I. 我就会得到这样的结果。

sudo mv offender.h /usr/local/include/
g++ -Wall -Werror -o test test.cpp

No Warning is triggered.

如果我从当前目录中包含头文件,怎么会出现警告,但如果我从预定义的包含目录中包含它,又会正常工作?我遗漏了什么?

已经用g++ 7.5.0(Ubuntu 18.04)和9.3.0(Ubuntu 20.04)测试过了,都产生了相同的输出。

编辑:澄清了问题

c++ g++ compiler-warnings
1个回答
4
投票

文件

声明操作系统和运行库接口的头文件通常不能用严格的C语言编写,因此,GCC对系统头文件中的代码进行了特殊处理。除了由'#warning'产生的警告(见诊断),所有的警告都会在GCC处理系统头文件时被抑制。

© www.soinside.com 2019 - 2024. All rights reserved.