eclipse c++ 加 MinGW GCC 生成Dll,以及调用Dll方法详解,
由于是纯C++的程序,只不过在这个Java 的eclipse平台上使用,十分尴尬
问题是,遇到当用eclipse编译C++代码生成Dll后,只生成了Dll文件却没有生成对应的lib文件,
问题是如何才能正确的再其他程序调用这个编译好的dll 文件,进行测试使用呢
这里需要使用的是,LoadLibraryA 函数与GetProcAddress函数进行获取对应函数
为了能够直接使用函数名,获取到对应函数,需要在导出函数时候加上,extern "C" __declspec(dllexport)
这是最简单的方式,使用c语言的方式编译,编译器不会对函数进行换名操作,(C++有函数重载的形式,一般会进行换名来区分不同函数)
不赘述了,网上对于如何导出动态库,导入动态库,教程也比较多
直接上代码
第一步,动态库程序
file -> new -> c++ Project -> project type 选择 shared library ->toolchains 选择MinGW GCC
project name 填写shared_library
点击完成,
第二部,添加两个文件
add.hpp add.cpp
/
/*
* add.hpp
*/
#ifndef ADD_HPP_
#define ADD_HPP_
extern "C" __declspec(dllexport) int sum(int a , int b);
#endif /* ADD_HPP_ */
/
#include "add.hpp"
extern "C" __declspec(dllexport) int sum(int a,int b){
return a+b;
}
/
然后右键项目,build Project
右键,properties -> resurce -> locations E:\eclipse_workspace\shared_library
复制路径,在路径的Debug文件夹下找到对应文件 libshared_library.dll
这里lib前缀, shared_library,工程名称 ,.dll后缀
只有dll文件,没有lib
测试程序
然后新建
file -> new -> c++ Project -> project type 选择 Executable , hello c++ Project ->toolchains 选择MinGW GCC
project name lib_test
配置属性
右键项目,properties -> c/c++ build ->settings
-> GCC c++ compiles
-> Includes 添加 "E:\eclipse_workspace\shared_library\src"
-> MinGW c++ Linker
->Libraries -> Libraries (-l) 添加 libshared_library
-> Library search path (-L) 添加 "E:\eclipse_workspace\shared_library\Debug"
配置之后可以找到对应的 头文件,和对应的dll 动态库文件
编写代码
/
//============================================================================
// Name : lib_test.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <windows.h>
using namespace std;
typedef int (*FunAdd)(int,int);
int main() {
HMODULE DLL = LoadLibraryA("libshared_library");
FunAdd sum = (FunAdd)GetProcAddress(DLL,"sum");
int a = 5;
int b = 3;
int c = sum(a,b);
cout << "sum(a,b) " << c << endl;
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
/
生成
build project
运行
run as
/
sum(a,b) 8
!!!Hello World!!!
/