VS2010下創建靜態鏈接庫和動態鏈接庫
下麵介紹一下用VS2010如何創建靜態鏈接庫和動態鏈接庫,並測試創建的庫。
1.靜態鏈接庫
打開VS2010,新建一個項目,選擇win32項目,點擊確定,選擇靜態庫這個選項,預編譯頭文件可選可不選。
在這個空項目中,添加一個.h文件和一個.cpp文件。名字我們起為static.h和static.cpp
static.h文件:
- #ifndef LIB_H
- #define LIB_H
- extern "C" int sum(int a,int b);
- #endif
static.cpp文件:
- #include "static.h"
- int sum(int a,int b)
- {
- return a+b;
- }
下麵說明如何調用靜態鏈接庫。
首先需要新建一個空項目,起名為test。將之前static項目下的static.h和static.lib這個2個文件複製到test項目的目錄下,並在工程中加入static.h文件。
新建一個test.cpp文件如下:
- #include <stdio.h>
- #include <stdlib.h>
- #include "static.h"
- #pragma comment(lib,"static.lib")
- int main()
- {
- printf("%d\n",sum(1,2));
- system("pause");
- return 0;
- }
#pragma comment(lib,"static.lib"),這一句是顯式的導入靜態鏈接庫。除此之外,還有其他的方法,比如通過設置路徑等等,這裏不做介紹。
2.動態鏈接庫
和創建靜態鏈接庫一樣,需要創建一個空的win32項目,選擇dll選項。創建dynamic.cpp和dynamic.h文件
dynamic.h文件:
- #ifndef DYNAMIC
- #define DYNAMIC
- extern "C" __declspec(dllexport)int sum(int a, int b);
- #endif DYNAMIC
dynamic.cpp文件:
- #include "dynamic.h"
- int sum(int a, int b)
- {
- return a+b;
- }
下麵介紹如何調用動態鏈接庫,這裏講的是顯式的調用。
在剛才的test項目下,把static.lib和static.h文件刪除,把dynamic.h和dynamic.dll複製到該目錄下,並在項目中添加dynamic.h文件,修改test.cpp文件為:
- #include <stdio.h>
- #include <stdlib.h>
- #include<Windows.h>
- #include "dynamic.h"
- int main()
- {
- HINSTANCE hDll=NULL;
- typedef int(*PSUM)(int a,int b);
- PSUM pSum;
- hDll = LoadLibrary(L"dynamic.dll");
- pSum = (PSUM)GetProcAddress(hDll,"sum");
- printf("%d\n",pSum(1,2));
- system("pause");
- FreeLibrary(hDll);
- return 0;
- }
編譯運行結果為:3
特別提示:
1.extern "C"中的C是大寫,不是小寫
2.如果從VS2010中直接運行程序,lib和dll需要放到test項目的目錄下;如果想雙擊項目test下的debug文件中的exe文件直接運行的話,需把lib和dll放入debug文件夾下。
最後更新:2017-04-03 05:40:14