閱讀519 返回首頁    go 阿裏雲 go 技術社區[雲棲]


VS2010下創建靜態鏈接庫和動態鏈接庫

下麵介紹一下用VS2010如何創建靜態鏈接庫和動態鏈接庫,並測試創建的庫。

1.靜態鏈接庫

打開VS2010,新建一個項目,選擇win32項目,點擊確定,選擇靜態庫這個選項,預編譯頭文件可選可不選。

在這個空項目中,添加一個.h文件和一個.cpp文件。名字我們起為static.h和static.cpp

static.h文件:

  1. #ifndef LIB_H  
  2. #define LIB_H  
  3.   
  4. extern "C" int sum(int a,int b);  
  5.   
  6. #endif

static.cpp文件:

  1. #include "static.h"  
  2.   
  3. int sum(int a,int b)  
  4. {  
  5.     return a+b;  
  6. }
編譯這個項目之後,會在debug文件夾下生成static.lib文件,這個就是我們需要的靜態鏈接庫。


下麵說明如何調用靜態鏈接庫。

首先需要新建一個空項目,起名為test。將之前static項目下的static.h和static.lib這個2個文件複製到test項目的目錄下,並在工程中加入static.h文件。

新建一個test.cpp文件如下:

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include "static.h"  
  4.   
  5. #pragma comment(lib,"static.lib")  
  6.   
  7. int main()  
  8. {  
  9.     printf("%d\n",sum(1,2));  
  10.     system("pause");  
  11.     return 0;  
  12. }


編譯運行可得結果:3

#pragma comment(lib,"static.lib"),這一句是顯式的導入靜態鏈接庫。除此之外,還有其他的方法,比如通過設置路徑等等,這裏不做介紹。


2.動態鏈接庫

和創建靜態鏈接庫一樣,需要創建一個空的win32項目,選擇dll選項。創建dynamic.cpp和dynamic.h文件

dynamic.h文件:

  1. #ifndef DYNAMIC  
  2. #define DYNAMIC  
  3.   
  4. extern "C" __declspec(dllexport)int sum(int a, int b);  
  5.   
  6. #endif DYNAMIC 

dynamic.cpp文件:

  1. #include "dynamic.h"  
  2.   
  3. int sum(int a, int b)  
  4. {  
  5.     return a+b;  
  6. }
編譯這個項目,會在debug文件夾下生成dynamic.dll文件。

下麵介紹如何調用動態鏈接庫,這裏講的是顯式的調用。

在剛才的test項目下,把static.lib和static.h文件刪除,把dynamic.h和dynamic.dll複製到該目錄下,並在項目中添加dynamic.h文件,修改test.cpp文件為:

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include<Windows.h>  
  4. #include "dynamic.h"  
  5. int main()  
  6. {  
  7.     HINSTANCE hDll=NULL;  
  8.     typedef int(*PSUM)(int a,int b);  
  9.     PSUM pSum;  
  10.     hDll = LoadLibrary(L"dynamic.dll");  
  11.     pSum = (PSUM)GetProcAddress(hDll,"sum");  
  12.     printf("%d\n",pSum(1,2));  
  13.     system("pause");  
  14.     FreeLibrary(hDll);  
  15.     return 0;  
  16. }

編譯運行結果為:3


特別提示:

1.extern "C"中的C是大寫,不是小寫

2.如果從VS2010中直接運行程序,lib和dll需要放到test項目的目錄下;如果想雙擊項目test下的debug文件中的exe文件直接運行的話,需把lib和dll放入debug文件夾下。



VS2010下創建靜態鏈接庫和動態鏈接庫

最後更新:2017-04-03 05:40:14

  上一篇:go 使用wordpress搭建博客過程中遇到的一些問題
  下一篇:go 如何分析命令行參數