QT进阶之动态库的创建和使用代码
时间: 2023-12-20 17:16:57 浏览: 74
以下是一个简单的例子,演示了如何在Qt中创建和使用动态库。
动态库工程代码(mylib.pro):
```
TEMPLATE = lib
CONFIG += dll
QT += core gui
HEADERS += mylib_global.h \
myclass.h
SOURCES += myclass.cpp \
mylib_global.cpp
TARGET = mylib
DESTDIR = ../bin
```
mylib_global.h文件:
```cpp
#ifndef MYLIB_GLOBAL_H
#define MYLIB_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(MYLIB_LIBRARY)
# define MYLIB_EXPORT Q_DECL_EXPORT
#else
# define MYLIB_EXPORT Q_DECL_IMPORT
#endif
#endif // MYLIB_GLOBAL_H
```
myclass.h文件:
```cpp
#ifndef MYCLASS_H
#define MYCLASS_H
#include "mylib_global.h"
#include <QObject>
class MYLIB_EXPORT MyClass : public QObject
{
Q_OBJECT
public:
explicit MyClass(QObject *parent = nullptr);
Q_INVOKABLE void doSomething();
};
#endif // MYCLASS_H
```
myclass.cpp文件:
```cpp
#include "myclass.h"
#include <QDebug>
MyClass::MyClass(QObject *parent) : QObject(parent)
{
}
void MyClass::doSomething()
{
qDebug() << "MyClass::doSomething() called.";
}
```
使用动态库的程序代码:
```cpp
#include <QCoreApplication>
#include <QLibrary>
#include "myclass.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 加载动态库
QLibrary myLib("mylib.dll");
if(!myLib.load())
{
qDebug() << "Failed to load library.";
}
// 获取MyClass类的指针
MyClass *myClass = (MyClass*)myLib.instance();
if(myClass == nullptr)
{
qDebug() << "Failed to get MyClass instance.";
}
else
{
// 调用MyClass的函数
myClass->doSomething();
}
return a.exec();
}
```
需要注意的是,在编译使用动态库的程序时,需要在.pro文件中添加LIBS += -lmylib或者LIBS += ../lib/mylib.dll(取决于动态库文件的名称和路径)。
阅读全文