聲明:下面這篇文章不是我寫的,源自:壹個叫,有容乃大 的博客
如何手工編寫動態鏈接庫(windows dll)
1.本例介紹在命令行(Console)環境下制作dll的方法
2.讀者動手前,請確保在windows中安裝有編譯、鏈接工具和必要的函數庫文件。
3.本例使用C語言實現.
4.本例中使用路徑均為我機器上的絕對路徑,讀者需根據實際情況調整。
工具要求:
Microsoft的編譯器cl.exe
MIcrosoft鏈接器link.exe
dll制作步驟:
1.編寫dll函數實現源代碼hello.c
#include
int say_hello(char* name)
{
printf( "hello %s\n ", name);
return 1;
}
2.編寫dll函數輸出定義文件hello.def.
LIBRARY hello
EXPORTS
say_hello @1
3.編譯dll源碼,生成dll,lib文件.
3.1 新建命令行窗口
3.2 設置PATH ?0?7 INCLUDE ?0?7 LIB 3個環境變量.
SET PATH=K:\vcnet\vc7\bin;%PATH%
SET INCLUDE=K:\vcnet\vc7\include;%INCLUDE%
SET LIB=K:\vsnet\Vc7\lib;%LIB%
3.3 編譯hello.c
cd K:\Source\dllsample (hello.c和hello.def所在目錄)
cl /c hello.c
3.4 鏈接hello.obj,生成hello.dll,hello.lib兩個文件.
link /def:hello.def /dll hello.obj
4.測試dll函數.
4.1 編寫測試代碼 test.c
extern int say_hello(char* name);
int main(int argc,char** argv)
{
say_hello( "robbie ");
return 0;
}
4.2 編譯測試代碼test.c
cl /c test.c
4.3 鏈接test.obj和 hello.lib,生成可執行文件test.exe
link test.obj hello.lib
4.4 運行test.exe,屏幕輸出:
hello robbie
至此,壹個dll構造完畢.
下面是我自己的壹點補充:
如果要在c++下,或者win32 mfc下使用標準c寫的dll,必須把上面的聲明
extern int say_hello(char* name);改成:extern "C " int say_hello(char* name);