tags:

views:

1974

answers:

5

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  A: 

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

Documentation

JaredPar
Thanks - but what would I use it for?
Scott J
For declaring COM interfaces and classes, for example, you use __declspec(uuid), for exporting functions sans a DEF file you use __declspec(dllexport), etc. The full list is quite long.
Seva Alekseyev
A: 

The canonical example is __declspec(dllexport) and __declspec(dllimport), which instruct the linker to import/export 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)

Alexander Gessler
+1  A: 

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.

Seva Alekseyev
+3  A: 

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.

AndiDog
+1  A: 

The declspec tells the compiler that the function lives in a DLL. If you are writing a function that will be exposed from a DLL you need to add declspec(dllexport) and if you are consuming a function or class from a DLL you would add declspec(dllimport). Generally the import part of this is done for you in the header file.

For more info, see here http://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx

Joel
That's just __declspec(dllimport). There are much more __declspec's out there.
Seva Alekseyev