通过cmake禁用特定库的警告

Disable the warning of specific libraries by cmake

本文关键字:警告 cmake 通过      更新时间:2023-10-16

我使用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:qt5T-i386-ntvcincludeQtCore/qhash.h(81) : warning C4127: conditional expression is constant
G:qt5T-i386-ntvcincludeQtCore/qlist.h(521) : warning C4127: conditional expression is constant
        G:qt5T-i386-ntvcincludeQtCore/qlist.h(511) : while compiling class template member function 'void QList<T>::append(const T &)'
        with
        [
            T=QString
        ]
        G:qt5T-i386-ntvcincludeQtCore/qstringlist.h(62) : see reference to class template instantiation 'QList<T>' being compiled
        with
        [
            T=QString
        ]

等等

这是不可能的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

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

例如,当您构建目标foo时,假设您想在Visual Studio 2019中禁用C4068: unknown pragma 'mark'警告。生成警告的Visual Studio编译器选项提到标志/wdnnnn抑制警告nnnn。因此,要抑制该警告,您可以使用以下命令更新CMakeLists.txt文件。

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