这是一个例子。并非所有事情都是完全必要的(例如 DLLMain),但我认为这些是您应该查找的内容 ;-)
SayHello.cpp
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
// see https://msdn.microsoft.com/en-us/library/56h2zst2.aspx : Decorated Names
extern "C" { // somehow making it superfluous to put the code in SayHello.cPP ...but anyway ;-)
// see https://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx : dllexport, dllimport
__declspec(dllexport) void say_hello()
{
printf("Hello DLL World!");
}
// see https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583%28v=vs.85%29.aspx : (optional) DllMain entry point
BOOL WINAPI DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
}
主文件
extern "C" { __declspec(dllimport) void say_hello(); } // we did this in SayHello.cpp, so we have to do it here too.
// otherwise the name wouldn't match
int main() {
say_hello();
return 0;
}
然后编译/链接
cl /D_USRDLL /D_WINDLL SayHello.cpp /LD /link /OUT:SayHello.dll
/LD 告诉链接器构建 DLL并使用 /MT,请参阅/MD、/MT、/LD(使用运行时库)。(通过 OUT: 参数,您可以更改 .dll 的名称;这里是默认值,仅用于演示目的。如果您省略它,您也可以跳过 /link 参数,因为不再有链接器参数。)
cl.exe /MT main.cpp /link /SUBSYSTEM:CONSOLE "SayHello.lib"
匹配 dll 的运行时库设置,创建控制台应用程序(main.cpp 有一个int main()
)并链接 SayHello 的存根库(而不是使用LoadLibrary("SayHello.dll") / GetProcAddress(...))