Deep analysis of creating DLLS in VC exporting global variables functions and classes
- 2020-04-01 23:40:01
- OfStack
One. Create DLL
1. Create a new Win32 empty project MathLib in VC;
2. Add precompiled header file stdafx.h, define import and export control symbol:
3. Add the header file mathlib.h containing the global variables, functions and classes to be exported:
4. Add the implementation file mathlib.cpp for the exported elements
Second, test the DLL created
Test code:
1. Create a new Win32 empty project MathLib in VC;
2. Add precompiled header file stdafx.h, define import and export control symbol:
//stdafx.h
#pragma once
#define MATHLIB_EXPORT
3. Add the header file mathlib.h containing the global variables, functions and classes to be exported:
//MathLib.h
#pragma once
#ifdef MATHLIB_EXPORT
#define MATHLIBAPI __declspec(dllexport)
#else
#define MATHLIBAPI __declspec(dllimport)
#endif
//macro
#define PI 3.14149
//Global variable
extern MATHLIBAPI int GlobalVariable;
//Function
MATHLIBAPI int Add(int a,int b);
//Class
class MATHLIBAPI Math
{
public:
int Multiply(int a,int b);
};
4. Add the implementation file mathlib.cpp for the exported elements
//MathLib.cpp
#include "stdafx.h"
#include "MathLib.h"
int GlobalVariable = 100;
int Add(int a,int b)
{
return a+b;
}
int Math::Multiply(int a,int b)
{
return a*b;
}
Second, test the DLL created
Test code:
#include "stdafx.h"
#include <iostream>
using namespace std;
#include "../MathLib/MathLib.h"
#pragma comment(lib,"../Debug/MathLib.lib")
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Pi = "<<PI<<endl;
cout<<"GlobalVariable = "<<GlobalVariable<<endl;
int a = 20,b = 30;
cout<<"a="<<a<<", "<<"b="<<b<<endl;
cout<<"a+b = "<<Add(a,b)<<endl;
Math math;
cout<<"a*b = "<<math.Multiply(a,b)<<endl;
return 0;
}