我们创建一个工程动态链接库,名称为DLL1,然后在DLL1.h中添加代码如下:
#ifdef DLL1_API_IMP
#else
#define DLL1_API_IMP __declspec(dllimport)
#endif
//导出类
class DLL1_API_IMP Test
{
public:
void output(int x, int y);
};
在DLL1.cpp中添加代码如下:
#include "stdafx.h"
#define DLL1_API_IMP __declspec(dllexport)
#include "DLL1.h"
#include <iostream>
void Test::output(int x, int y)
{
std::cout << x + y<< std::endl;
}
右键点击项目----选择重新生成。会发现生成DLL1.dll 和 DLL1.lib文件
创建一个控制台项目,将DLL1.h 、DLL1.dll 和 DLL1.lib三个文件,拷贝到该项目下,添加代码如下:
#include "stdafx.h"
#include <Windows.h>
#pragma comment(lib,"DLL1.lib")
#include "DLL1.h"
int _tmain(int argc, _TCHAR* argv[])
{
Test t;
t.output(3, 2);
system("pause");
return 0;
}
运行查看结果即可。
#ifdef DLL1_API_IMP
#else
#define DLL1_API_IMP __declspec(dllimport)
#endif
//导出类
class Test
{
public:
void <span style="font-family: Arial, Helvetica, sans-serif;">DLL1_API_IMP </span><span style="font-family: Arial, Helvetica, sans-serif;"> output(int x, int y);</span>
void test();
};
cpp文件如下
#include "stdafx.h"
#define DLL1_API_IMP __declspec(dllexport)
#include "DLL1.h"
#include <iostream>
void Test::output(int x, int y)
{
std::cout << x + y<< std::endl;
}
void Test::test()
{
std::cout <<”... test ...“<< std::endl;
}
重新生成后,并将DLL1.h 、DLL1.dll 和 DLL1.lib三个文件,拷贝到测试项目下,添加代码如下:
#include "stdafx.h"
#include <Windows.h>
#pragma comment(lib,"DLL1.lib")
#include "DLL1.h"
int _tmain(int argc, _TCHAR* argv[])
{
Test t;
t.output(3, 2);
// t.test() //error
system("pause");
return 0;
}
运行测试即可。