Qt之创建并使用静态链接库
我们一起看看如何创建与使用静态链接库。
创建步骤与共享库一致,唯一的区别是库类型选择:静态链接库。
- StaticLibrary.pro
QT += core gui widgets
TARGET = StaticLibrary
TEMPLATE = lib
CONFIG += staticlib
HEADERS += staticlibrary.h
SOURCES += staticlibrary.cpp
TEMPLATE = lib 定义生成的为库文件(如果是app则为可执行程序)
CONFIG += staticlib 定义导出库的类型为静态链接库
- staticlibrary.h
#ifndef STATICLIBRARY_H
#define STATICLIBRARY_H
#include
class StaticLibrary : public QWidget
{
Q_OBJECT
public:
explicit StaticLibrary(QWidget *parent = 0);
void updateBackground();
int subtract(int a, int b);
private slots:
void onClicked();
};
int add(int a, int b);
#endif // STATICLIBRARY_H
- staticlibrary.cpp
#include "staticlibrary.h"
#include
#include
#include
StaticLibrary::StaticLibrary(QWidget *parent)
: QWidget(parent)
{
QPushButton *pButton = new QPushButton(this);
pButton->setText("Test Static Library");
connect(pButton, SIGNAL(clicked()), this, SLOT(onClicked()));
}
void StaticLibrary::onClicked()
{
QMessageBox::information(this, "Tip", "Static Library...");
}
void StaticLibrary::updateBackground()
{
QTime time;
time = QTime::currentTime();
qsrand(time.msec() + time.second()*1000);
int nR = qrand() % 256;
int nG = qrand() % 256;
int nB = qrand() % 256;
QPalette palette(this->palette());
palette.setColor(QPalette::Background, QColor(nR, nG, nB));
this->setPalette(palette);
}
int StaticLibrary::subtract(int a, int b)
{
return a - b;
}
int add(int a, int b)
{
return a + b;
}
执行qmake,然后构建,会生成一个StaticLibrary.lib文件。这样我们的创建静态链接库就彻底完成了。
如果使用QtCreater 会生成StaticLibrary.a(静态链接库)和StaticLibrary.o(obj文件)文件。
下面我们来看看如何去应用这个共享库:
首先新建一个测试工程,然后新建一个文件夹StaticLibrary,并将将刚才生成的文件(StaticLibrary.a、staticlibrary.h)拷贝到该目录下(也可以不拷贝,这里为了更清楚地说明路径及引用)。
TestStaticLibrary.pro
QT += core gui widgets
TARGET = TestStaticLibrary
TEMPLATE = app
INCLUDEPATH += ./StaticLibrary
#-L$$PWD/StaticLibrary -lStaticLibrary
LIBS += $$PWD/StaticLibrary/StaticLibrary.a
HEADERS += StaticLibrary/staticlibrary.h
SOURCES += main.cpp
main.cpp
#include "StaticLibrary/staticlibrary.h"
#include
#include
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
StaticLibrary w;
w.resize(400, 200);
w.updateBackground();
w.show();
int nSubtract = w.subtract(10, 4);
int nAdd = add(5, 5);
QMessageBox::information(NULL, "Tip", QString("subtract:%1 add:%2").arg(nSubtract).arg(nAdd));
return a.exec();
}
这样我们就完成了静态库的创建与使用,是不是比动态库更简单呢!
总结:1、QTCreator生成的静态链接库叫xxx.a文件
2、静态链接库在编译的时候使用,需要.h和.a两个文件
3、更换.a 文件需要重新编译程序,一般很少用到