之前在网上一直查不到关于把类打包成dll文件的程序,今天自己写了个测试程序,供大家参考
一、生成类的dll文件
1.我是在vs2008上测试的,建立工程,在选择建立何种类型的工程的时候,勾上application type中的dll;
2.添加一个头文件,命名为mydll.h,这个头文件就是我们测试时候要用接口文件,代码如下:
- #ifndef _MYDLL_H_
 - #define _MYDLL_H_
 - #ifdef MYLIBDLL
 - #define MYLIBDLL extern "C" _declspec(dllimport)
 - #else
 - #define MYLIBDLL extern "C" _declspec(dllexport)
 - #endif
 - class _declspec(dllexport) testDll{//关键在这个地方,如果这个地方出错,你所建立的dll文件也就不能用了
 - private:
 - int a;
 - public:
 - testDll();
 - void setA();
 - int getA();
 - };
 - #endif
 
3.添加一个源文件,命名为mydll.cpp,这个是类的实现文件:
- #include "stdafx.h"
 - #include <iostream>
 - #include "mydll.h"
 - using namespace std;
 - testDll::testDll(){
 - cout<<"test dll"<<endl;
 - a = 11;
 - }
 - int testDll::getA()
 - {
 - return a;
 - }
 - void testDll::setA(){
 - a = 33;
 - }
 
4.最后其他的文件都是vs2008自动生成的,不用去修改,现在编译下,生成dll和lib文件;
二、测试自己生成的dll和lib文件
1、建立工程,在选择建立exe应用程序类型;
2、把刚才生成的dll和lib文件拷到这个工程目录下,另外把mydll.h也拷贝过来(关键);
3、忘了一点,在vs2008中,在linker中把dll 和lib的目录加进去,还要把lib名字加入到addtional dependencies中;
4、在测试文件的主程序中添加如下代码:
- #pragma comment(lib, "dllOne.lib")
 - #include "stdafx.h"
 - #include <iostream>
 - #include "mydll.h"
 - using namespace std;
 - int _tmain(int argc, _TCHAR* argv[])
 - {
 - testDll* tmp = new testDll();
 - cout<<tmp->getA()<<endl;
 - tmp->setA();
 - cout<<tmp->getA()<<endl;
 - getchar();
 - return 0;
 - }
 
4,运行,测试下。