开发者

Visual Studio C++: When should I be using __declspec(dllimport)?

开发者 https://www.devze.com 2023-02-05 01:25 出处:网络
I had a question about DLL building / linking in Visual Studio 2005 and later. Basically my understanding and experience is this:

I had a question about DLL building / linking in Visual Studio 2005 and later. Basically my understanding and experience is this:

To build a DLL, I specify the project properties to build a DLL, and then I but __declspec(dllexport) in front of any functions or members that I want to publically expose from the DLL. Building the project will result in a DLL, a Lib, and a header file that can be deployed as say an API or something.

On the other end, to have your other compiled executable application dynamically link to the DLL and use its functions, you simply need to have your executable project include the header files and link with the small lib file that was created when the DLL was built. As long and the compiled application can find the DLL, everything will work.

That has been my experience and that is also how the Microsoft DLL building tutorial described everything on MSDN开发者_Go百科. I am wondering: is this standard practice? When would you ever need to use __declspec(dllimport) anywhere? Am I missing something?

Thanks!


Yes you would use __declspec(dllimport) and you generally have a macro that controls whether a source file either exports (if it's part of your DLL) or imports (if it's part of the using-executable) symbols.

In your DLL you can set a manifest constant to the build settings of some sort, say 'BUILDING_MY_DLL' and then create the macro like this within your header file:

#ifdef BUILDING_MY_DLL
#define MY_DLL_EXPORT __declspec(dllexport)
#else
#define MY_DLL_EXPORT __declspec(dllimport)
#endif

and then decorate your exported functions like this:

MY_DLL_EXPORT int func(int y);

You can also export entire classes this way too:

class MY_DLL_EXPORT InterestingClass
{
...
};
0

精彩评论

暂无评论...
验证码 换一张
取 消