2014-09-21 148 views
1

是否可以向g ++添加额外的警告标志,以便它会在以下代码中警告我有关单元化的b变量?更好的编译器警告?

#include <iostream> 
using namespace std; 
int main() { 
    int a, b; 
    cin >> a; 
    while (a>0) b++; 
    cout << a; 
} 

编辑:我忘了提,我试图打开这个其他问题列出的标志: Flags to enable thorough and verbose g++ warnings但没有触发。 (“Tickled!”,如我所知)。

+0

你有没有尝试'g ++ -Wall -Wextra'? – 2014-09-21 17:40:40

+1

我的测试显示海湾警备局没有发出警告,并带有重大警告组(-Wall,-Wextra,-pedantic)和Clang发出警告。 – chris 2014-09-21 17:41:01

+1

您可以添加编译标志即。 -壁。 HTTP://计算器。com/questions/11714827/how-to-turn-on-literally-all-of-gccs-warnings – risque 2014-09-21 17:41:28

回答

7

你以后的选项可能-Wmaybe-uninitialized-Wuninitialized。这两个都是-Wall选项的一部分,它打开了这些选项,还有许多其他警告(-Wxxx选项与警告相关)。

有关gcc警告选项的完整文档可在以下位置阅读:Options to Request or Suppress Warnings gcc文档中。

您可能还会发现-Wextra可能对您有用(单独使用或与-Wall结合使用)。 -Wextra也启用-Wuninitialized,但它有其他项目并不总是由-Wall设置,我喜欢看到的东西(如-Wunused-parameter-Wunused-but-set-parameter),虽然这不是特定于此位代码。


这就是说......(是啊,有一个“上面写着”)......我似乎不能胳肢错误与海湾合作委员会,它是此功能可在http://gcc.godbolt.org

扩展一些你的代码是专门的文档中的-Wmaybe-uninitialized

#include <iostream> 
using namespace std; 
int main() { 
    int a, b; 
    int x, y, z; 
    // warning: variable ‘y’ set but not used [-Wunused-but-set-variable] 
    cin >> a; 
    while (a>0) b++; 
    switch(a) { 
    case 1: x = 1; y = 1; z++; break; 
    // warning: ‘z’ may be used uninitialized in this function [-Wmaybe-uninitialized] 
    case 2: x = 4; y = 2; break; 
    case 3: x = 5; y = 3; 
    } 
    cout << a; 
    cout << b; 
    cout << x; 
} 

这说明是痒痒了一批闲置和成套警告的尝试。我能够得到z变量产生的错误,但由于某种原因b++在while循环不会产生错误或警告与gcc(使用gcc 4.9.0进行测试)。

Warnings with gcc 4.9.0

铛版本3.4.1,但是,并产生与这些命令行选项警告两个bz

Warnings with clang 3.4.1

虽然-Wall-Wextra产生警告后,由于某些原因,他们不会产生这个特定的代码在海湾合作委员会4.9.0

+0

http://coliru.stacked-crooked.com/a/14e57e5734b03dbf – chris 2014-09-21 17:45:02

+0

@chris'#clang ++ -std = C++ 1y' ...它不是gcc。 – 2014-09-21 17:45:55

+0

'#'是一条评论。看下面两行。保留我经常使用的一些东西并且在它们之间切换而不必再次形成它们是很容易的。 – chris 2014-09-21 17:46:58