gpt4 book ai didi

c++ - 使用#pragma warning push/pop 是临时改变警告级别的正确方法吗?

转载 作者:IT老高 更新时间:2023-10-28 12:12:21 24 4
gpt4 key购买 nike

有时很难编写完全不会发出警告的 C++ 代码。然而,启用警告是个好主意。因此,通常需要禁用围绕某些特定构造的警告,并在所有其他代码段中启用它们。

到目前为止,我已经看到了两种方法。

第一种是使用#pragma warning(push)#pragma warning(pop):

 #pragma warning( push )
#pragma warning( disable: ThatWarning )
//code with ThatWarning here
#pragma warning( pop )

第二种是使用#pragma warning(default):

 #pragma warning( disable: ThatWarning )
//code with ThatWarning here
#pragma warning( default: ThatWarning )

我在第二个变体中看到的问题是它丢弃了原始警告级别 - 警告可能在此之前已关闭,或者其警告级别可能已更改。使用 default 会丢弃这些更改。

第一种方法看起来很干净。有什么问题吗?有没有更好的方法来达到同样的效果?

最佳答案

这将适用于多个编译器(以及不同版本的编译器)。

标题“推送”

#if defined(__clang__)
# pragma clang diagnostic push
#endif

#if defined(_MSC_VER)
# pragma warning(push)
#endif

#if defined(YOUR_FAVORITE_COMPILER)
# pragma your compiler push warning
#endif

标题“弹出”

#if defined(__clang__)
# pragma clang diagnostic pop
#endif

#if defined(_MSC_VER)
# pragma warning(pop)
#endif

一些警告

#if defined(__clang__)
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wunused-variable"
# if __has_warning("-Wnew-special-warning")
# pragma clang diagnostic ignored "-Wnew-special-warning"
# endif
#endif

#if defined(_MSC_VER)
# pragma warning(disable: 4100) // unreferenced formal parameter
# if _MSC_VER > _MSC_SOME_VERSION
# pragma warning(disable: xxxx) // disable one more for special version
# endif
#endif

用法

// This code reports warnings
// ...
#include <ignore_compiler_warning/push>
#include <ignore_compiler_warning/warning_type_1>
#include <ignore_compiler_warning/warning_type_2>
#include <ignore_compiler_warning/warning_type_3>
// This code ignores warnings type_{1,2,3}
// ...
#include <ignore_compiler_warning/pop>
// Back to reporting warnings
// ...

另外包括 guard 可以检查没有双推/弹出/禁用警告编译指示。

更新

关于c++ - 使用#pragma warning push/pop 是临时改变警告级别的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4193476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com