【问题标题】:QT warning level suggestionQT 警告级别建议
【发布时间】:2011-02-14 02:40:29
【问题描述】:

您在编译 QT 项目时使用的警告级别是多少?

当我使用 W4 编译时,我收到很多警告,例如:

C4127: conditional expression is constant

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

你的做法是什么?

谢谢。

【问题讨论】:

标签: c++ qt coding-style warnings warning-level


【解决方案1】:

我在几年前遇到了与您完全相同的问题,即将编译器设置为 4 级警告以捕获尽可能多的潜在问题。当时,我与 Qt 签订了支持合同,并问他们为什么他们的代码会产生如此多的警告。他们的回答是,他们从不保证他们的代码会在没有任何警告的情况下编译。只有他们的代码才能正确运行。

经过几次尝试,我开始用编译指示包围 Qt 头文件以禁用警告,如下所示 -

#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库文件也有这个问题。

【讨论】:

    【解决方案2】:

    就我个人而言,我只是使用 qmake 默认生成的 Makefile...假设我可以相信诺基亚的人会让它生成为当前构建环境做正确事情的 Makefile。

    我确实看到 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.
    

    【讨论】:

    • 如果我没记错的话,这些警告选项是在你运行 qmake 生成 make 文件时使用的,而不是在你运行生成的 makefile 时使用的。
    【解决方案3】:

    在您的 .pro 文件中使用 CONFIG += warn_on

    the documentation

    选项

    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.
    

    【讨论】:

      【解决方案4】:

      如果您在 Visual Studio 中使用 Q_ASSERT,则所有警告推送/弹出内容都将不起作用,因为宏已“实例化”到位,远远落后于您的标题。 所以我建议重新定义 Q_ASSERT:

      #ifdef NDEBUG
      #undef Q_ASSERT
      #define Q_ASSERT(x) __noop
      #endif
      

      【讨论】:

        【解决方案5】:

        根据 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
        

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

        【讨论】:

          猜你喜欢
          • 2013-01-16
          • 2011-04-15
          • 2011-03-23
          • 1970-01-01
          • 2011-09-12
          • 2015-05-22
          • 2014-01-10
          • 2014-10-23
          • 1970-01-01
          相关资源
          最近更新 更多