MinGW编译dll并引用

dll大法好!这是总所周知的。


这篇文章以A+B/A-B为范例,来介绍如何在MinGW下编译dll并引用。

  • 首先你要安装MinGW,并配置好环境变量(不配置环境变量也行,就是麻烦)。

  • 我们新建一段.cpp代码,命名为dll.cpp( 什么破名字 ),写入:
#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;
}


  • 接下来建立一个名为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 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



  • 题外话:同时引用两个dll


    我们在刚才的目录下新建一段代码,名为dllx.cpp(呃……),里面写上:

#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的计算结果?

猜你喜欢

转载自www.cnblogs.com/Return-blog/p/12327366.html