I. Creating a DLL
1. In VC, a new Win32 empty project mathlib;
2. Add precompiled Header file stdafx.h, define import export control symbols:
Copy Code code as follows:
StdAfx.h
#pragma once
#define Mathlib_export
3. Add the header file MathLib.h that contains the global variables, functions, and classes to export:
Copy Code code as follows:
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 for the exported element MathLib.cpp
Copy Code code as follows:
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;
}
Two, test the DLL you created
Test code:
Copy Code code as follows:
#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;
}