[[deprecated]] results in error instead of warning in Visual Studio

Viewed 3528

According to cppreference [[deprecated("message string")]] we should be able to use the symbol but in VS results in error instead.

For example I wan't to issue a warning for ANSI methods in UNICODE builds and vice versa:

#ifdef UNICODE
[[deprecated("This method does not work well in UNICODE builds")]]
#endif // UNICODE
    void f() {}

compiler doesn't let me compile, but standard says the attribute should allow usage but issue a warning message.

How to resolve this?, btw. my project is set to maximum conformance with the standard.

What ever the reason for VS going against the standard, is there a better way to issue a warning for above case?

4 Answers

Very much late to the party, but this cost me a couple of hours this morning.

By default, Visual Studio and the sdl (Security Development Lifecycle) compile flag treat [[deprecated]] as an error. Whether or not you agree with this or not, that's how they do it.

To fix this go to Configuration Properties -> C/C++ -> Command Line and add /sdl /w34996

The /wX part represents the severity of the warning, and the rest is the error you want to report as a warning.

I hope this saves people some time.

is there a better way to issue a warning for above case?

There's no other way of warning about usage of a function than deprecation attribute in standard C++ at least that I know of.

Msvc has other alternatives such as #pragma deprecated(f), but those are not better.

How to resolve this?

Assuming you haven't configured your compiler to treat warnings as errors, you could proceed with writing a bug report to the maintainers.

I haven't tested it with Visual Studio, but in my case the following helped and probably is more generic:

On that error usually warnings are treated as errors with the compiler flag -Werror, that is automatically set in Visual Studio. That is the reason way a class or function marked with [[deprecated]] results in an error. To avoid explicitly that error and output it just as a warning, the compiler flag -Werror -Wno-error=deprecated-declarations can be set. In CMake it would look like:

add_compile_options(-Werror -Wno-error=deprecated-declarations)
Related