Search code examples
cwindowspragma

Difference between __pragma(deprecated) and __declspec(deprecated)


To declare an object as deprecated in C/C++ under Visual Studio, you have three solutions:

  • #pragma deprecated(X)
  • __pragma(deprecated(X))
  • __declspec(deprecated(X))

The first two ones are the same, except that only the second one can be used inside a macro; I've put the first one only for completeness. The third one seems to be the most used in the dev community.

I wonder what is the difference between the last two ones. According to the documentation on MSDN here and here, I understand that there is no difference. What is strange in that case is that a different warning code is raised depending on what you're using: C4995 for the pragma-case, C4996 for the declspec-case.

So does somebody knows if there is actually a difference (any tiny one), or why these directives don't raise the same warning code?


Solution

  • See deprecated (C++):

    (Microsoft specific) With the exceptions noted below, the deprecated declaration offers the same functionality as the deprecated pragma:

    • The deprecated declaration lets you specify particular forms of function overloads as deprecated, whereas the pragma form applies to all overloaded forms of a function name.
    • The deprecated declaration lets you specify a message that will display at compile time. The text of the message can be from a macro.
    • Macros can only be marked as deprecated with the deprecated pragma.

    For #pragma vs. __pragma, see Pragma Directives and the __Pragma Keyword:

    The __pragma() Keyword

    Microsoft specific

    The compiler also supports the __pragma keyword, which has the same functionality as the #pragma directive, but can be used inline in a macro definition.


    It makes sense to note, as @Deduplicator mentioned, that C++14 introduces the [[deprecated]] attribute.

    7.6.5 Deprecated attribute [dcl.attr.deprecated]

    The attribute-token deprecated can be used to mark names and entities whose use is still allowed, but is discouraged for some reason. [ Note: in particular, deprecated is appropriate for names and entities that are deemed obsolescent or unsafe. —end note ]