通过 cmake 禁用特定库的警告

use*_*849 4 c++ qt boost cmake

我正在使用 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()
Run Code Online (Sandbox Code Playgroud)

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

编辑:我在谈论 3rd 方库的用法。示例是

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
        ]
Run Code Online (Sandbox Code Playgroud)

等等

doq*_*tor 5

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
Run Code Online (Sandbox Code Playgroud)