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

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?


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++)


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)