1. 创建静态动态库
1.1类型选择"静态链接库"
剩余的操作使用默认设置即可。
1.2 创建完成后,添加接口,因为是静态链接库,所以我们不需要导出接口,使用时只需要包含头文件即可使用
目录结构
Library.pro
#-------------------------------------------------
#
# Project created by QtCreator 2019-08-21T17:10:12
#
#-------------------------------------------------
QT -= gui
TARGET = Library
TEMPLATE = lib
CONFIG += staticlib
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += library.cpp
HEADERS += library.h
unix {
target.path = /usr/lib
INSTALLS += target
}
library.h
#ifndef LIBRARY_H
#define LIBRARY_H
//函数接口
double Divide(int a,int b);
class Library
{
public:
Library();
//类静态成员函数接口
static int Add(int a,int b);
static int Del(int a,int b);
//类成员函数接口
int Multi(int a ,int b);
};
#endif // LIBRARY_H
library.cpp
#include "library.h"
Library::Library()
{
}
int Library::Add(int a, int b)
{
return a+b;
}
int Library::Del(int a, int b)
{
return a - b;
}
int Library::Multi(int a, int b)
{
return a*b;
}
double Divide(int a,int b)
{
return (double)a/(double)b;
}
1.3 编译完成后,在输出目录下,liblibrary.a即为静态库,使用msvc编译位lib文件
2. 使用动态库
2.1 创建控制台程序
2.2 将静态库文件copy到指定目录下,并设置路径。
dlltest.pro
QT += core
QT -= gui
CONFIG += c++11
TARGET = dlltest
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
#HEADERS += $$PWD/Library/include/library.h
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
LIBS += $$PWD/Library/lib/libLibrary.a
main.cpp
#include <QCoreApplication>
#include <QDebug>
#include "Library/include/library.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int num1 = 10;
int num2 = 3;
qDebug()<<"静态成员函数1接口"<<Library::Add(num1,num2);
qDebug()<<"静态成员函数2接口"<<Library::Del(num1,num2);
Library lib;
qDebug()<<"普通成员函数接口"<<lib.Multi(num1,num2);
qDebug()<<"普通函数接口"<<Divide(num1,num2);
return a.exec();
}
2.3 编译完成后,不需要copy动态库,即可运行