C/C++中動態(tài)鏈接庫的創(chuàng)建和調(diào)用

字號:

動態(tài)連接庫的創(chuàng)建步驟:
    一、創(chuàng)建Non-MFC DLL動態(tài)鏈接庫
    1、打開File —> New —> Project選項(xiàng),選擇Win32 Dynamic-Link Library —>sample project
    —>工程名:DllDemo
    2、新建一個.h文件DllDemo.h
    以下是引用片段:
    #ifdef DllDemo_EXPORTS
    #define DllAPI __declspec(dllexport)
    #else
    #define DllAPI __declspec(dllimport)
    extern "C" //原樣編譯
    {
    DllAPI int __stdcall Max(int a,int b); //__stdcall使非C/C++語言內(nèi)能夠調(diào)用API
    }
    #endif
    3、在DllDemo.cpp文件中導(dǎo)入DllDemo.h文件,并實(shí)現(xiàn)Max(int,int)函數(shù)
    以下是引用片段:
    #include "DllDemo.h"
    DllAPI int __stdcall Max(int a,int b)
    {
    if(a==b)
    return NULL;
    else if(a>b)
    return a;
    else
    return b;
    }
    4、編譯程序生成動態(tài)連接庫
    二、用.def文件創(chuàng)建動態(tài)連接庫DllDemo.dll。
    1、刪除DllDemo工程中的DllDemo.h文件。
    2、在DllDemo.cpp文件頭,刪除 #include DllDemo.h語句。
    3、向該工程中加入一個文本文件,命名為DllDemo.def并寫入如下語句:
    LIBRARY MyDll
    EXPORTS
    Max@1
    4、編譯程序生成動態(tài)連接庫。