VC中创建DLL,导出全局变量,函数和类

一.创建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: }

你可能感兴趣的:(全局变量)