动态连接库创建与使用
项目创建
注意选择成shared library
此时新建的项目pro文件:
QT -= gui
TARGET = library
TEMPLATE = lib
DEFINES += LIBRARY_LIBRARY
DEFINES += QT_DEPRECATED_WARNINGS
SOURCES += \
library.cpp
HEADERS += \
library.h
unix {
target.path = /usr/lib
INSTALLS += target
}
注意其Template为lib,且声明了一个LIBRARY_LIBRARY
对于global.h文件建议直接拷贝到library.h,这样发布的时候只需要给别人一个.h文件
library.h
#ifndef LIBRARY_H
#define LIBRARY_H
#include <QtCore/qglobal.h>
#if defined(LIBRARY_LIBRARY)
# define LIBRARYSHARED_EXPORT Q_DECL_EXPORT
#else
# define LIBRARYSHARED_EXPORT Q_DECL_IMPORT
#endif
class LIBRARYSHARED_EXPORT Library {
public:
Library();
int sum(int a, int b);
};
int LIBRARYSHARED_EXPORT sum(int a, int b);
#endif // LIBRARY_H
pro声明的宏在这里用上了,做了一个判断,如果有定义则LIBRARYSHARED_EXPORT=Q_DECL_EXPORT,否则等于Q_DECL_IMPORT,也就是说在这个lib项目里是导出的意思,在其他项目因为给别人的只有.h文件并没有LIBRARY_LIBRARY的定义,所以是导入。从而实现不做任何修改即可发布.h文件。
将global.h拷贝到library.h也是为了只提供一个文件,否则若忘记了提供global.h调用方会提示缺少文件。
library.cpp
Library::Library() {
}
int Library::sum(int a,