QT警告级别建议

6

您编译QT项目时使用的警告级别是什么?

当我使用W4编译时,会出现许多警告,例如:

C4127: conditional expression is constant

我应该在W3编译,还是找其他方法处理W4的警告,比如:添加新的头文件并使用#pragma(在这里提到了C++编码标准:101条规则、指南和最佳实践)。

你们的做法是什么?

谢谢。


我不明白为什么一个常量条件表达式会成为问题。 - Carson Myers
2
在我看来,如果它是常量,那么你根本不需要它。 微软对此警告的解释: http://msdn.microsoft.com/zh-cn/library/6t66728h(VS.80).aspx - metdos
5个回答

11

几年前我遇到了与你完全相同的问题,即将编译器设置为级别4警告,以便尽可能地捕获潜在的问题。当时我与Qt签订了支持合同,并询问他们为什么他们的代码生成如此多的警告。他们的回应是,他们从未保证他们的代码可以无警告编译通过,只保证其可以正确运行。

经过多次尝试,我开始使用Pragma来禁用警告,具体操作如下所示 -

#pragma warning(push,3)  // drop compiler to level 3 and save current level
#include <QString>
#include <QVariant>
#include <QStack>
#include <QLabel>
#include <QtGui/QTableWidget>
#pragma warning(pop)    // restore compiler warning level

通过这种方式,您只会使用较低的警告级别编译Qt头文件。或者以任何需要消除警告的级别进行编译。可能仍会出现一些个别警告,因此您可以提高警告级别或使用某些选项禁用个别警告。

#pragma warning(disable: 4700)

一些 Boost 库文件也存在这个问题。


4

就我个人而言,我只使用qmake默认生成的Makefiles……因为我可以相信诺基亚的工程师能够生成当前构建环境下做正确的事情的Makefiles。

不过,我注意到qmake还可以接受一些关于警告的可选参数:

The level of warning information can be fine-tuned to help you find problems in your project file:

-Wall 
qmake will report all known warnings.
-Wnone 
No warning information will be generated by qmake.
-Wparser 
qmake will only generate parser warnings. This will alert you to common pitfalls and potential problems in the parsing of your project files.
-Wlogic 
qmake will warn of common pitfalls and potential problems in your project file. For example, qmake will report whether a file is placed into a list of files multiple times, or if a file cannot be found.

1
如果我没记错的话,那些警告选项是用于运行 qmake 生成 make 文件时使用的,而不是用于运行生成的 makefile。 - Caleb Huitt - cjhuitt

1
如果您在Visual Studio中遇到Q_ASSERT问题,那么所有的警告推送/弹出操作都不会起作用,因为宏是在头文件之后的位置“实例化”的。所以我建议重新定义Q_ASSERT:
#ifdef NDEBUG
#undef Q_ASSERT
#define Q_ASSERT(x) __noop
#endif

1
在您的.pro文件中使用CONFIG += warn_on
请参阅文档

Option

warn_on
  The compiler should output as many warnings as possible.
  This is ignored if warn_off is specified.

warn_off
  The compiler should output as few warnings as possible.

0

根据user2846246的回答,我发现在编译使用Qt的任何库之前添加以下内容就行了(在我的情况下,该库在Visual Studio中使用预编译头文件,因此我只需将代码添加到该头文件中):

#ifndef _DEBUG
    #undef  Q_ASSERT
    #define Q_ASSERT(x) __noop
    #undef  Q_ASSERT_X
    #define Q_ASSERT_X(cond, where, what) __noop
#endif

这很好,因为我不喜欢降低整个库的警告级别。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接