是否有跨平台的方法可以在C++中禁用已弃用的警告?

Is there a cross-platform way to disable deprecated warnings in C++?

本文关键字:警告 跨平台 方法 是否 C++      更新时间:2023-10-16

我有一个库,我正在重构一些功能。我用下面定义的itkLegacyMacro标记了一些旧方法。这些已弃用的方法将从库自己的单元测试中调用。有没有办法禁用适用于所有(或至少大多数(编译器的弃用警告?

itkLegacyMacro:

// Setup compile-time warnings for uses of deprecated methods if
// possible on this compiler.
#if defined( __GNUC__ ) && !defined( __INTEL_COMPILER ) && ( __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ >= 1 ) )
#define itkLegacyMacro(method) method __attribute__( ( deprecated ) )
#elif defined( _MSC_VER )
#define itkLegacyMacro(method) __declspec(deprecated) method
#else
#define itkLegacyMacro(method) method
#endif

库中的方法定义:

class X {
itkLegacyMacro(void oldMethod());
void newMethod(); }

从单元测试调用的方法:

X testX;
testX.newMethod(); //test the new stuff
testX.oldMethod(); //test the old stuff too!

最后一行会导致在编译时发出警告。我希望这个库测试已弃用的功能,但在编译时没有警告。这可能吗?正在使用C++11。

据我所知__declspec(...)是一个Microsoft扩展,无论如何都不是跨平台的。

您可以使用宏来控制它

#ifdef _MSC_VER
#define DEPRECATED __declspec(deprecated)
#else 
#define DEPRECATED
#endif
DEPRECATED void someDeprecatedFunction()

自C++14以来也有[[deprecated("because")]]

若要仅为单元测试关闭它,可以执行以下操作

#ifndef SUPPRESS_DEPRECATE_FUNCTIONS
#define DEPRECATED __declspec(deprecated)
#else
#define DEPRECATED
#endif

然后在单元测试中#define SUPPRESS_DEPRECATE_FUNCTIONS,或使用-DSUPPRESS_DEPRECATE_FUNCTIONS编译。或者,您可以在单元测试中创建一个特殊的标头,以#pragma警告抑制。类似的东西

#if defined( __GNUC__ ) && !defined( __INTEL_COMPILER ) && ( __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ >= 1 ) )
#pragma for gcc
#elif defined( _MSC_VER )
#pragma for msvc
#else
// nothing
#endif
#include "your_library_header.h"

然后,单元测试仅在任何其他库标头之前包含此标头。