新浪博客

Qt之创建并使用静态链接库

2015-08-29 12:57阅读:
继上一节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文件。这样我们的创建静态链接库就彻底完成了。
下面我们来看看如何去应用这个共享库:
首先新建一个测试工程,然后新建一个文件夹StaticLibrary,并将将刚才生成的文件(StaticLibrary.lib、staticlibrary.h)拷贝到该目录下(也可以不拷贝,这里为了更清楚地说明路径及引用)。
TestStaticLibrary.pro
QT += core gui widgets TARGET = TestStaticLibrary TEMPLATE = app INCLUDEPATH += ./StaticLibrary #-L$$PWD/StaticLibrary -lStaticLibrary LIBS += $$PWD/StaticLibrary/StaticLibrary.lib 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(); }
这样我们就完成了静态库的创建与使用,是不是比动态库更简单呢!O(∩_∩)O哈哈~
效果如下:
Qt之创建并使用静态链接库
注:
技术在于交流、沟通,转载请注明出处并保持作品的完整性。
作者:一去丶二三里 原文:http://blog.sina.cn/dpool/blog/s/blog_a6fb6cc90102vsdx.html?vt=4

我的更多文章

下载客户端阅读体验更佳

APP专享