C++动态库导出类

有时候希望在将整个类导出到动态库以供调用,如何做呢?示例如下:

我用VS2010首先创建了一个空的动态库工程用来生成一个供测试用的动态库,紧接着有创建一个空的win32控制台程序用来调用动态库的类,然后将这两个工程放到一个解决方案中。在各工程中新建头文件和源文件如下图:


其中,动态库工程的头文件(header.h)如下所示:

#ifndef HEADER_H
#define HEADER_H
 #ifdef AFX_CLASS
 #define AFX_EX_CLASS _declspec(dllexport)
 #else
 #define AFX_EX_CLASS _declspec(dllimport)
 #endif
#endif

class AFX_EX_CLASS cls
{
public:
	cls(int i,int j);
	int add();
private:
	int m;
	int n;
};
动态库工程的源文件(source.cpp)如下所示:

#define AFX_CLASS
#include "stdafx.h"
#include "header.h"

cls::cls(int i,int j)
{
	m = i;
	n = j;
}

int cls::add()
{
	return m+n;
}
点击生成后在debug目录生成了动态库文件(DLL.dll)和引入库文件(DLL.lib).

将这两个文件复制到测试工程的源文件目录下

测试工程的源文件(src.cpp)如下所示:

#include ".\\..\\..\\DLL\\DLL\\\header.h"
#pragma comment(lib,"DLL.lib")
#include <iostream>
using namespace std;

void main()
{
	cls *clsObj = new cls(2,3);
	int num = clsObj->add();
	cout<<"result : "<<num<<endl;
	system("pause");
}
测试结果:





猜你喜欢

转载自blog.csdn.net/GK_2014/article/details/48456927