C++ mark as deprecated

Viewed 105967

I have a method in an interface that I want to deprecate with portable C++. When I Googled for this all I got was a Microsoft specific solution; #pragma deprecated and __declspec(deprecated).

A second prize solution would be to ifdef a MSVC and a GCC solution.

7 Answers

This should do the trick:

#ifdef __GNUC__
#define DEPRECATED(func) func __attribute__ ((deprecated))
#elif defined(_MSC_VER)
#define DEPRECATED(func) __declspec(deprecated) func
#else
#pragma message("WARNING: You need to implement DEPRECATED for this compiler")
#define DEPRECATED(func) func
#endif

...

//don't use me any more
DEPRECATED(void OldFunc(int a, float b));

//use me instead
void NewFunc(int a, double b);

However, you will encounter problems if a function return type has a commas in its name e.g. std::pair<int, int> as this will be interpreted by the preprocesor as passing 2 arguments to the DEPRECATED macro. In that case you would have to typedef the return type.

Edit: simpler (but possibly less widely compatible) version here.

In GCC you can declare your function with the attribute deprecated like this:

void myfunc() __attribute__ ((deprecated));

This will trigger a compile-time warning when that function is used in a .c file.

You can find more info under "Diagnostic pragmas" at http://gcc.gnu.org/onlinedocs/gcc/Pragmas.html

Dealing with portable projects it's almost inevitable that you at some point need a section of preprocessed alternatives for a range of platforms. #ifdef this #ifdef that and so on.

In such a section you could very well conditionally define a way to deprecate symbols. My preference is usually to define a "warning" macro since most toolchains support custom compiler warnings. Then you can go on with a specific warning macro for deprecation etc. For the platforms supporting dedicated deprecation methods you can use that instead of warnings.

For Intel Compiler v19.0, use this as __INTEL_COMPILER evaluates to 1900:

#  if defined(__INTEL_COMPILER)
#    define DEPRECATED [[deprecated]]
#  endif

Works for the following language levels:

  • C++17 Support (/Qstd=c++17)
  • C++14 Support (/Qstd=c++14)
  • C++11 Support (/Qstd=c++11)
  • C11 Support (/Qstd=c11)
  • C99 Support (/Qstd=c99)

The Intel Compiler has what appears a bug in that it does not support the [[deprecated]] attribute on certain language elements that all other compilers do. For an example, compile v6.0.0 of the (remarkly superb) {fmtlib/fmt} library on GitHub with Intel Compiler v19.0. It will break. Then see the fix in the GitHub commit.

Related