我想在编译我自己的代码时禁用来自库标头的 C++ 代码中的特定已知警告。有 clang 和 gcc 特定的方法来禁用警告。完成的方式几乎相同。
对于clang:
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-local-typedefs"
#include <library.h>
#pragma clang diagnostic pop
对于gcc:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#include <library.h>
#pragma GCC diagnostic pop
有没有一种干净的方法来抑制这些警告,并且可以跨 clang 和 GCC 移植?
嗯,干净是一个相对术语,但这是我们在这个 C 库的测试代码中采用的方法,它旨在支持所有 GCC、clang 和 MSVC。正如@Thomas 提到的,
_Pragma(GCC Whatever)
也适用于 clang,所以我们可以使用它。
一般机制:
// Multi-compiler-compatible local warning suppression
#if defined(__GNUC__) || defined(__clang__)
#define DO_PRAGMA(X) _Pragma(#X)
#define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push)
#define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop)
#define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored #warningName)
#elif defined(_MSC_VER)
#define DISABLE_WARNING_PUSH __pragma(warning( push ))
#define DISABLE_WARNING_POP __pragma(warning( pop ))
#define DISABLE_WARNING(warningNumber) __pragma(warning( disable : warningNumber ))
#else
// unknown compiler, ignoring suppression directives
#define DISABLE_WARNING_PUSH
#define DISABLE_WARNING_POP
#endif
用于禁用特定警告的宏:
#if defined(__GNUC__) || defined(__clang__)
// specific disable's for the warnings we care about
#define DISABLE_WARNING_PRINTF_FORMAT DISABLE_WARNING(-Wformat)
#define DISABLE_WARNING_PRINTF_FORMAT_EXTRA_ARGS DISABLE_WARNING(-Wformat-extra-args)
#if defined(__clang__)
#define DISABLE_WARNING_PRINTF_FORMAT_OVERFLOW
#define DISABLE_WARNING_PRINTF_FORMAT_INVALID_SPECIFIER DISABLE_WARNING(-Wformat-invalid-specifier)
#else
#define DISABLE_WARNING_PRINTF_FORMAT_OVERFLOW DISABLE_WARNING(-Wformat-overflow)
#define DISABLE_WARNING_PRINTF_FORMAT_INVALID_SPECIFIER
#endif
#elif define(_MSC_VER)
// TODO: Need to actually determine the appropriate MSVC warning numbers :-(
#define DISABLE_WARNING_PRINTF_FORMAT
#define DISABLE_WARNING_PRINTF_FORMAT_EXTRA_ARGS
#define DISABLE_WARNING_PRINTF_FORMAT_OVERFLOW
#define DISABLE_WARNING_PRINTF_FORMAT_INVALID_SPECIFIER
#else
// unknown compiler
#define DISABLE_WARNING_PRINTF_FORMAT
#define DISABLE_WARNING_PRINTF_FORMAT_EXTRA_ARGS
#define DISABLE_WARNING_PRINTF_FORMAT_OVERFLOW
#define DISABLE_WARNING_PRINTF_FORMAT_INVALID_SPECIFIER
#endif
在您的程序中,您可以包装各个指令或块,如下所示:
DISABLE_WARNING_PUSH
DISABLE_WARNING_PRINTF_FORMAT
DISABLE_WARNING_PRINTF_FORMAT_EXTRA_ARGS
DISABLE_WARNING_PRINTF_FORMAT_INVALID_SPECIFIER
sprintf_(buffer, "%.4.2s", "123456");
DISABLE_WARNING_POP