What is __declspec and when do I need to use it?

前端 未结 6 1165
耶瑟儿~
耶瑟儿~ 2020-11-30 18:08

I have seen instances of __declspec in the code that I am reading. What is it? And when would I need to use this construct?

相关标签:
6条回答
  • 2020-11-30 18:16

    The canonical examples are __declspec(dllimport) and __declspec(dllexport), which instruct the linker to import and export (respectively) a symbol from or to a DLL.

    // header
    __declspec(dllimport) void foo();
    
    
    // code - this calls foo() somewhere in a DLL
    foo();
    

    (__declspec(..) just wraps up Microsoft's specific stuff - to achieve compatibility, one would usually wrap it away with macros)

    0 讨论(0)
  • 2020-11-30 18:22

    This is a Microsoft specific extension to the C++ language which allows you to attribute a type or function with storage class information.

    Documentation

    __declspec (C++)

    0 讨论(0)
  • 2020-11-30 18:22

    It is mostly used for importing symbols from / exporting symbols to a shared library (DLL). Both Visual C++ and GCC compilers support __declspec(dllimport) and __declspec(dllexport). Other uses (some Microsoft-only) are documented in the MSDN.

    0 讨论(0)
  • 2020-11-30 18:23

    Another example to illustrate the __declspec keyword:

    When you are writing a Windows Kernel Driver, sometimes you want to write your own prolog/epilog code sequences using inline assembler code, so you could declare your function with the naked attribute.

    __declspec( naked ) int func( formal_parameters ) {}
    

    Or

    #define Naked __declspec( naked )
    Naked int func( formal_parameters ) {}
    

    Please refer to naked (C++)

    0 讨论(0)
  • 2020-11-30 18:24

    I know it's been eight years but I wanted to share this piece of code found in MRuby that shows how __declspec() can bee used at the same level as the export keyword.

    /** Declare a public MRuby API function. */
    #if defined(MRB_BUILD_AS_DLL)
    #if defined(MRB_CORE) || defined(MRB_LIB)
    # define MRB_API __declspec(dllexport)
    #else
    # define MRB_API __declspec(dllimport)
    #endif
    #else
    # define MRB_API extern
    #endif
    
    0 讨论(0)
  • 2020-11-30 18:25

    Essentially, it's the way Microsoft introduces its C++ extensions so that they won't conflict with future extensions of standard C++. With __declspec, you can attribute a function or class; the exact meaning varies depending on the nature of __declspec. __declspec(naked), for example, suppresses prolog/epilog generation (for interrupt handlers, embeddable code, etc), __declspec(thread) makes a variable thread-local, and so on.

    The full list of __declspec attributes is available on MSDN, and varies by compiler version and platform.

    0 讨论(0)
提交回复
热议问题