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
請按任意鍵繼續. . .