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

时间:2018-03-09 11:17:53

标签: 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;
}

我们可以在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 

但是,当我们使用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$

在终端我们只能看到错误......
如何看待这些警告?
任何命令?看警告?

1 个答案:

答案 0 :(得分:4)

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

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

g++ -Wall test1.cpp -o test1

打印:

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]

正如消息所示,-Wuninitialized足以发出此类警告,但我建议您使用-Wall作为初学者,并关闭真正不需要的警告需要在某些遗留代码上,最好的方法是启用额外的警告,并将警告变成错误,以便人们必须修复它们:

g++ -Wall -Wextra -Werror ...

另请注意,您无法依赖此警告来检测所有未初始化的变量。在某些复杂的情况下,编译器无法确定它是否已初始化(请参阅why am I not getting an "used uninitialized" warning from gcc in this trivial example?)。为此,你需要一个更专业的工具,如Valgrind。

相关问题