验证环境:ubuntu18.04+Qt5.14 / win10+Qt5.14
验证内容:以命名空间的方式导出类,导出函数带参数/不带参数的函数。
1、导出变量
导出的动态库本身需要提供头文件,在命名空间中直接定义变量即可。
#ifndef COMMON_LIB_H
#define COMMON_LIB_H
#include common_global.h # 导出宏定义
namespace common # 命名空间common
{
int a = 1;
}
#endif // COMMON_LIB_H
2、导出函数
此处隐去其它部分,命名空间约束的导出出函数,将导出函数语句放置在命名空间内,之后在源文件.cpp中实现。
// common.h
namespace common
{
// ...
extern "C" COMMONSHARED_EXPORT int fun();
}
// .cpp
#include "common.h"
void common::fun()
{
std::cout<< "run test::fun();" <<std::endl;
std::cout<< "common::a=" << common::a <<std::endl;
}
3、导出类
导出类与导出函数一样,将导出类的代码放在命名空间内,源文件中实现对应函数,头文件爱你只做定义。
# common.h
namespace common
{
// ...
class COMMONSHARED_EXPORT test
{
public:
test(){}
void fun();
int a;
};
}
// common.cpp
#include "common.h"
using namespace common;
int test::fun()
{
std::cout<<"run test::fun();"<<std::endl;
}
4、动态库调用
.pro中引用动态库
# 引用common
INCLUDEPATH += /home/code/c++project/common
LIBS += -L/home/code/c++project/common/lib_r -lcommon
main.cpp中调用
#include common.h
using namespace std;
int main()
{
std::cout<< "common::a = "<<common::a<<std::endl;
common::fun();
common::test o;
o.fun();
std::cout<< "o.a = "<<o.a<<std::endl;
}
上一篇:Qt动态库封装工程最佳实践