在linux中,qt裡面已經集成了最新的開發平台QT Creator,下面是我練習調用動態庫(.so文件)的例程:
1、打開QT Creator,點擊File-》New...菜單,選擇C++ Libarary工程,點擊下一步,輸入工程名稱(本例為zsz)即可,這沒什麼可說的。
工程文件(.pro)程序清單
# -------------------------------------------------
# Project created by QtCreator 2009-03-02T10:09:35
# -------------------------------------------------
TARGET = zsz
TEMPLATE = lib
CONFIG += plugin
DEPENDPATH += .
INCLUDEPATH += .
SOURCES += mylib.cpp
HEADERS += mylib.h
mylib.h文件程序清單:
#ifndef MYLIB_H
#define MYLIB_H
#ifdef Q_WS_WIN //表示在windows環境
#define MY_EXPORT __declspec(dllexport)
#else
#define MY_EXPORT
#endif
class mylib {
public:
int mymax(int i, int j);
int add(int i, int j);
};
extern "C" MY_EXPORT int diff(int i, int j);
#endif // MYLIB_H
mylib.cpp文件程序清單:
#include "mylib.h"
extern "C" MY_EXPORT int mylib::mymax(int i,int j)
{
if(i>=j)
return i;
else
return j;
}
extern "C" MY_EXPORT int mylib::add(int i,int j)
{
return i+j;
}
extern "C" MY_EXPORT int diff(int i, int j)
{
if(i>=j)
return i-j;
else
return j-i;
}
對該工程進行編譯,生成libzsz.so文件。
2、創建一個GUI工程,並把zsz工程下的mylib.h和libzsz.so兩個文件拷貝到當前目錄下。
工程文件程序清單:
# -------------------------------------------------
# Project created by QtCreator 2009-03-02T10:15:03
# -------------------------------------------------
TARGET =
TEMPLATE = app
QT += svg
DEPENDPATH += .
INCLUDEPATH += .
LIBS += ./libzsz.so
SOURCES += main.cpp
HEADERS += mylib.h
main.cpp中的程序為:
#include <qapplication.h>
#include <QPushButton>
#include <QLibrary>
#include <QtDebug>
#include "mylib.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPushButton hello("Hello world!zwd");
hello.resize(400, 200);
mylib a;
qDebug()<<"In the two numbers 9 and 15,maxxer is "<< a.mymax(15,9);
qDebug()<<"Add the two numbers 9 and 15,result is "<< a.add(15,9);
qDebug()<<"Diff the two numbers 9 and 15,result is "<< diff(15,9);
hello.show();
return app.exec();
}