Qt解决方案中添加动态链接库项目

来源:互联网 发布:信捷编程手册 编辑:程序博客网 时间:2024/05/19 01:10

动态链接的好处: 生成执行文件小,修改程序后重新编译部分少。
如何添加动态链接库项目:
解决方案->添加新建项目->qt projects -> qt library (输入项目名为abc),然后生成一个新项目,包含abc.h abc.cpp abc_global.h三个文件,打开abc.h可以看到class ABC_EXPORT abc 的定义(在abc_global.h中有#define ABC_EXPORT Q_DECL_EXPORT,再次跟踪,有define Q_DECL_EXPORT __declspec(dllexport),^_^,找到目标了吧),再在abc.h删除类abc,加入
extern "C"
{
    STATIC_EXPORT WndStatic* NewForm();   //NewForm为导出函数
}
在abc.cpp中定义NewForm函数。
完成之后在原来的项目中调用QLibrary::resolve ("abc", "NewForm") ,Loads the library fileName and returns the address of the exported symbol symbol.返回类NewForm的指针。
typedef WndStatic* (*FUNC)();
    FUNC func;
    func = (FUNC)QLibrary::resolve("abc", "NewForm");
    if (func)
    {}
最后注意要在原来的项目中->属性->配置属性->c/c++->常规,附加包含目录中添加新项目所在的目录,然后在原项目中#include 相应的文件。

 

======================

对于调用DLL的方法,Qt原来本身就有相应的类来实现,用起来和Win32的步骤差不多。下面是代码,已经编译通过。在控制台依次输入qmake –project、qmake、 nmake,即可。

#include

#include

#include

//动态链接不需要包含LTM8000D.h头文件

typedef int ( *pcom_open)(int , int , int ); //定义函数指针

int main(int argc, char *argv[])

{

int ret; //函数返回值

int port=1; //端口

int baud=0; //波特率

int rtsdtr=0; //串行口485方向控制设置:

QApplication a(argc, argv);

QLabel label1(”label-1″); //显示打印信息,将就着用了。。。

QLabel label2(”label-2″);

QLibrary mylib(”LTM8000D.DLL”);

if(mylib.load())

{

label1.setText(”load DLL success!…”);

pcom_open open=(pcom_open)mylib.resolve(”ltm_com_open”);//“ltm_com_open”为DLL包含的实际函数名,必须实际存在

if(open)

{ ret=open(port, baud, rtsdtr); //在这里调用DLL里的函数

label2.setText(”resolve ok…”);

}

else

{

label1.setText(”resolve failed…”);

}

}else

{

label2.setText(”load DLL failed…”);

}

label1.show();

label2.show();

return a.exec();

}

总结:类似于调用DLL的交叉编程使用的场合很多,还可以用Qt生成DLL,给其他工具调用。说到底,VC和Qt等本质上都是一样的,只是提供了不同的C++库。