dll大法好!这是总所周知的。
这篇文章以A+B/A-B为范例,来介绍如何在MinGW下编译dll并引用。
首先你要安装MinGW,并配置好环境变量(不配置环境变量也行,就是麻烦)。
#include <iostream>
using namespace std;
#define EXPORT __declspec(dllexport)
extern "C"{
int EXPORT a_b(int a,int b); //计算A+B
int EXPORT a__b(int a,int b); //计算A-B
}
int a_b(int a,int b){
return a+b;
}
int a__b(int a,int b){
return a-b;
}
#include <iostream>
#include <cstdio>
using namespace std;
#define EXPORT __declspec(dllimport)
extern "C"
{
int EXPORT a_b(int a,int b);
int EXPORT a__b(int a,int b);
}
int main(){
cout << a_b(10,100*10) << endl;
cout << a__b(10*99, 100) << endl;
cin.get();
return 0;
}
现在来编译,打开cmd,输入命令 g++ C:\dll.cpp -shared -o C:\dll.dll -Wl,--out-implib,dll.lib
来把刚刚的 dll.cpp
编译成.dll。
接着输入 g++ -ldll test.cpp -o test.exe
来把 test.cpp 编译为 test.exe ,并且引用刚刚的 dll.dll。
怎么样?不出意外的话,你的目录下就会多出个test.exe,我们双击运行他。
输出的结果:
1010
890
#include <iostream>
using namespace std;
#define EXPORT __declspec(dllexport)
extern "C"{
int EXPORT a_x_b(int a,int b);
}
int a_x_b(int a,int b){
return a*b;
}
并把test.cpp改成如下代码:
#include <iostream>
#include <cstdio>
using namespace std;
#define EXPORT __declspec(dllimport)
extern "C"
{
int EXPORT a_b(int a,int b);
int EXPORT a__b(int a,int b);
int EXPORT a_x_b(int a,int b);
}
int main(){
cout << a_b(10,100*10) << endl;
cout << a__b(10*99, 100) << endl;
cout << a_x_b(10*10, 10) << endl;
cin.get();
return 0;
}
然后编译,输入命令 g++ C:\dllx.cpp -shared -o C:\dllx.dll -Wl,--out-implib,dllx.lib
来把刚刚的 dllx.cpp
编译成.dll。
接着再把test.exe编译一遍,输入命令 g++ -ldll -ldllx test.cpp -o test.exe
来编译test.exe。
怎么样,运行这个exe,是不是输出了10 * 10 * 10的计算结果?
原文:https://www.cnblogs.com/Return-blog/p/12327366.html