【问题标题】:Disable the warning of specific libraries by cmake通过 cmake 禁用特定库的警告
【发布时间】:2015-08-01 02:40:37
【问题描述】:

我正在使用 boost、Qt 和其他库来开发一些应用程序并使用 cmake 作为我的 make 工具。为了早点解决问题,我决定开启最强警告标志(感谢mloskot

if(MSVC)
  # Force to always compile with W4
  if(CMAKE_CXX_FLAGS MATCHES "/W[0-4]")
    string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
  else()
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4")
  endif()
elseif(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX OR
"${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
  # Update if necessary
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-long-long -pedantic")
endif()

到目前为止一切都很好,但这会引发很多关于我正在使用的库的警告,是否可以通过 cmake 禁用特定文件夹、文件或库的警告?

编辑: 我说的是第三方库的使用。例子是

G:\qt5\T-i386-ntvc\include\QtCore/qhash.h(81) : warning C4127: conditional expression is constant

G:\qt5\T-i386-ntvc\include\QtCore/qlist.h(521) : warning C4127: conditional expression is constant
        G:\qt5\T-i386-ntvc\include\QtCore/qlist.h(511) : while compiling class template member function 'void QList<T>::append(const T &)'
        with
        [
            T=QString
        ]
        G:\qt5\T-i386-ntvc\include\QtCore/qstringlist.h(62) : see reference to class template instantiation 'QList<T>' being compiled
        with
        [
            T=QString
        ]

等等

【问题讨论】:

  • 图书馆的警告是什么意思?你自己编译你的库吗?通常,您只会收到有关您编译的内容的警告。或者你在谈论你的图书馆的使用?你到底想达到什么目的?
  • 仅对第三方库禁用警告但在代码中启用警告并不容易。
  • @drescherjm 然后我会使用正则表达式来过滤掉与第三方库相关的警告

标签: c++ qt boost cmake


【解决方案1】:

CMake 无法做到这一点,因为这样的事情在 MSVC 中是不可能的。但是您可以使用 pragma 指令禁用源代码中的警告。您将需要确定它们来自哪个标头、警告编号并仅禁用该标头的警告。例如:

#ifdef _MSC_VER
#pragma warning(disable: 4345) // disable warning 4345
#endif
#include <boost/variant.hpp>
#ifdef _MSC_VER
#pragma warning(default: 4345) // enable warning 4345 back
#endif

【讨论】:

  • 这正是我对这个问题发表评论时所想的。
  • 还有一个带push/pop的语法:#pragma warning(push) #pragma warning(disable : 4345) #pragma warning(pop)
【解决方案2】:

如果您通过调用target_compile_options (reference) 设置相关编译器标志来禁用它们,那么您可以在构建任何目标时禁用特定警告。

例如,假设您要在构建目标 foo 时禁用 Visual Studio 2019 中的 C4068: unknown pragma 'mark' 警告。 Visual Studio compiler options to generate warnings 提到标志 /wdnnnn 抑制警告 nnnn。因此,要抑制该警告,您可以使用以下命令更新您的 CMakeLists.txt 文件。

if(MSVC)
    target_compile_options(foo 
        PRIVATE
            "/wd4068;" # disable "unknown pragma 'mark'" warnings
    )
endif()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-21
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 2010-11-07
    相关资源
    最近更新 更多