VS2013建立並使用DLL
阿新 • • 發佈:2020-08-19
轉載:https://blog.csdn.net/weixin_39345003/article/details/80782218
1.DLL檔案
DLL(Dynamic Link Library)檔案為動態連結庫檔案,又稱“應用程式拓展”,是軟體檔案型別。在Windows中,許多應用程式並不是一個完整的可執行檔案,它們被分割成一些相對獨立的動態連結庫,即DLL檔案,放置於系統中。當我們執行某一個程式時,相應的DLL檔案就會被呼叫。一個應用程式可使用多個DLL檔案,一個DLL檔案也可能被不同的應用程式使用,這樣的DLL檔案被稱為共享DLL檔案。
2.建立DLL專案
建立win32應用控制檯程式,取名為mydll,點選DLL選項。
新建goods.h 和goods.cpp 檔案
goods.h
#pragma once #ifdef MYDLL_EXPORTS #define MYDLL_API __declspec(dllexport) #else #define MYDLL_API __declspec(dllimport) #endif #include <iostream> #include <string> using namespace std; class MYDLL_API GOODS {public: GOODS::GOODS(); GOODS::~GOODS(); int setname(string name); int setnum(int num); int setperunit(int perunit); int printinfo(); int getcost(); private: string m_name; int m_num; int m_perunit; };
goods.cpp
#include "專案原始檔下新增.def檔案。新增方法:新增—新建項—程式碼—模組定義檔案。 最後生成解決方案,編譯成功後可以在debug資料夾下發現mydll.dll和mydll.lib檔案。goods.h" GOODS::GOODS() {} GOODS::~GOODS() {} int GOODS::setname(string name) { m_name = name; return 0; } int GOODS::setnum(int num) { m_num = num; return 0; } int GOODS::setperunit(int perunit) { m_perunit =perunit; return 0; } int GOODS::printinfo() { cout <<"name: " << m_name << endl; cout << "num: " << m_num << endl; cout << "perunit: " << m_perunit << endl; return 0; } int GOODS::getcost() { int cost = m_num*m_perunit; return cost; }
3.呼叫DLL專案
新建一個win32控制檯的空專案,取名usemydll,然後引用dll步驟如下:
1.專案->屬性->配置屬性->VC++ 目錄-> 在“包含目錄”裡新增標頭檔案goods.h所在的目錄
2.專案->屬性->配置屬性->VC++ 目錄-> 在“庫目錄”裡新增標頭檔案mydll.lib所在的目錄
3.專案->屬性->配置屬性->連結器->輸入-> 在“附加依賴項”裡新增“mydll.lib”
4.將dll專案下的debug檔案中的mydll.dll複製到當前專案的debug資料夾中
新建新增main.cpp檔案
main.cpp
#include "goods.h" int main() { GOODS book; book.setname("book"); book.setnum(2); book.setperunit(10); book.printinfo(); cout << "cost: "<<book.getcost() << endl; return 0; }