原来用过将函数封装为dll,今天遇到要将全局变量进行封装导出和导入,按照网上的一些资料进行实验总是出错,找到一个对的,记录下。

转自:http://luwenjie0904.blog.163.com/blog/static/96561541201131173412247/

一.创建DLL

1.在VC中新建一个Win32空项目MathLib;

 2.添加预编译头文件stdafx.h,定义导入导出控制符号:

 
  
  1: //stdafx.h  
  2: #pragma once  
  3: #define MATHLIB_EXPORT
3.添加包含要导出的全局变量,函数和类的头文件MathLib.h:
 
  
  1: //MathLib.h  
  2: #pragma once  
  3:   
  4: #ifdef MATHLIB_EXPORT  
  5: #define MATHLIBAPI __declspec(dllexport)  
  6: #else  
  7: #define MATHLIBAPI __declspec(dllimport)  
  8: #endif  
  9:   
 10: //macro  
 11: #define PI 3.14149  
 12:   
 13: //Global variable  
 14: extern MATHLIBAPI int GlobalVariable;  
 15:   
 16: //Function  
 17: MATHLIBAPI int Add(int a,int b);  
 18:   
 19: //Class  
 20: class MATHLIBAPI Math  
 21: {  
 22: public:  
 23:  int Multiply(int a,int b);  
 24: };
4.添加所导出元素的实现文件MathLib.cpp
 
  
  1: //MathLib.cpp  
  2: #include "stdafx.h"  
  3: #include "MathLib.h"  
  4:   
  5: int GlobalVariable = 100;  
  6:   
  7: int Add(int a,int b)  
  8: {  
  9:  return a+b;  
 10: }  
 11:   
 12: int Math::Multiply(int a,int b)  
 13: {  
 14:  return a*b;  
 15: }

二,测试所创建的DLL

测试代码:

 
  
  1: #include "stdafx.h"  
  2: #include <iostream>  
  3: using namespace std;  
  4:   
  5: #include "../MathLib/MathLib.h"  
  6: #pragma comment(lib,"../Debug/MathLib.lib")  
  7:   
  8: int _tmain(int argc, _TCHAR* argv[])  
  9: {  
 10:  cout<<"Pi = "<<PI<<endl;  
 11:   
 12:  cout<<"GlobalVariable = "<<GlobalVariable<<endl;  
 13:   
 14:  int a = 20,b = 30;  
 15:  cout<<"a="<<a<<", "<<"b="<<b<<endl;  
 16:  cout<<"a+b = "<<Add(a,b)<<endl;  
 17:   
 18:  Math math;  
 19:  cout<<"a*b = "<<math.Multiply(a,b)<<endl;  
 20:   
 21:  return 0;  
 22: }

注意:在测试lib的程序的开始可以不对全局变量进行声明直接用,要声明的话用 extern  int _declspec(dllimport)  a;
 

另外帖一个错的,试了好几遍都不对

http://hi.baidu.com/%CE%DA%C9%AA%B6%FB%D0%A6%C1%CB/blog/item/aa3ff8feb088ddf1fc037fe5.html