终端不显示程序的警告...如何在终端中查看它们?

0 c++ ubuntu warnings gnome-terminal

这是我用 vim 编辑器编写的一个简单程序:

#include <iostream>
using namespace std;

int main()
{
    int a;
    int b, c ;
    a=(b+c+11)/3;
    cout << "x=" << a;
    cout << "\n";
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

我们可以在windows中的Visual Studio中看到警告:

...error(s), 2 warning(s)
...\test1.cpp(7) : warning c4700: local variable 'b' used without having been initialized 
...\test1.cpp(7) : warning c4700: local variable 'c' used without having been initialized 
Run Code Online (Sandbox Code Playgroud)

但是,当我们使用 gnome-terminal 时,我们看不到警告:

SSS@SSS:~/.cpp$ g++ test1.cpp -o test1
SSS@SSS:~/.cpp$ chmod +x test1
SSS@SSS:~/.cpp$ ./test1
x=10925
SSS@SSS:~/.cpp$
Run Code Online (Sandbox Code Playgroud)

在终端中我们只能看到错误...
如何查看这些警告?
有什么命令可以查看警告吗?

Jea*_*bre 5

Visual Studio 默认警告级别与默认警告级别不同g++

您需要启用警告(我建议-Wall)才能看到它们。

g++ -Wall test1.cpp -o test1
Run Code Online (Sandbox Code Playgroud)

印刷:

test1.cpp: In function 'int main()':
test1.cpp:8:9: warning: 'b' is used uninitialized in this function [-Wuninitialized]
     a=(b+c+11)/3;
        ~^~
test1.cpp:8:9: warning: 'c' is used uninitialized in this function [-Wuninitialized]
Run Code Online (Sandbox Code Playgroud)

正如消息所暗示的-Wuninitialized那样,对于这种警告来说已经足够了,但我建议您作为初学者使用,如果您确实-Wall需要在某些遗留代码上使用不需要的警告,最好的方法是启用额外的警告,并将警告变成错误,以便人们必须修复它们:

g++ -Wall -Wextra -Werror ...
Run Code Online (Sandbox Code Playgroud)

另请注意,您不能依赖此警告来检测所有未初始化的变量。在复杂的情况下,编译器无法决定它是否已初始化(看看为什么在这个简单的示例中我没有从 gcc 收到“使用未初始化”警告?)。为此,您需要一个更专业的工具,例如 Valgrind。