使用VS2008創建一個DLL文件的方法

1.新建一個C++工程(testDLL)
File -> New -> Project
     -> Visual C++ -> Class Library

Name裏面填testDLL

2.修改相關文件
將testDLL.h文件修改爲
// testDLL.h
extern "C" int MyAdd(int a,int b);

將testDLL.cpp文件修改爲
// This is the main DLL file.

#include "stdafx.h"

#include "testDLL.h"

int MyAdd(int a,int b)
{
 return (a+b);
}

向工程裏面添加testDLL.def文件,內容爲
LIBRARY "testDLL"
EXPORTS
MyAdd @1

3.編譯
選擇 Build -> Build testDLL
此時在Debug目錄下會出現testDLL.dll文件和testDLL.lib文件.

4.引用dll文件
新建一個test3工程,裏面包含test3.cpp和testDLL.h文件,
testDLL.h的文件內容爲:
// testDLL.h

#pragma comment(lib,"testDLL.lib")
extern "C" _declspec(dllimport) int MyAdd(int a,int b);

 


test3.cpp文件的內容如下:
#include <iostream>
using namespace std;

#include "testDLL.h"

 

void main()
{
 int c = MyAdd(1,2);
 cout<<"hello.1+2="<<c<<endl;
}

運行結果爲:
hello.1+2=3
請按任意鍵繼續. . .


http://blog.sina.com.cn/s/blog_571ae3fa0100mwki.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章