1.qmake方式生成和调用动态库
链接:https://blog.csdn.net/lywzgzl/article/details/42805991
2.cmake方式生成和调用动态库
2.1创建共享库项目
Cmake新建一个Qt Creator项目,在CMakeLists.txt中添加如下代码
#-------------------------------------- 搜索软件包 --------------------------------------
find_package(Qt5Widgets REQUIRED)
find_package(Qt5Network REQUIRED)
set(CMAKE_AUTOMOC ON)
#-------------------------------------- 包含头文件 --------------------------------------
include_directories(${Qt5Widgets_INCLUDE_DIRS})
include_directories(${Qt5Network_INCLUDE_DIRS})
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
#-------------------------------------- -添加项目- --------------------------------------
FILE(GLOB_RECURSE HEADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/*.h*)
FILE(GLOB_RECURSE SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/*.c*)
add_library(${PROJECT_NAME} SHARED
${HEADER_FILES}
${SOURCE_FILES}
) #STATIC or SHARED
target_link_libraries(${PROJECT_NAME}
${Qt5Widgets_LIBRARIES}
${Qt5Network_LIBRARIES}
)
#-------------------------------------- -设置输出- --------------------------------------
set(OUTPUT_LIB_DIR ${PROJECT_BINARY_DIR}/lib
CACHE PATH "Output directory for libraries")
file(MAKE_DIRECTORY ${OUTPUT_LIB_DIR})
file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/${PROJECT_NAME})
set(LIBRARY_OUTPUT_PATH ${OUTPUT_LIB_DIR})
#-------------------------------------- -安装项目- --------------------------------------
install(TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}
LIBRARY DESTINATION ${LIBRARY_OUTPUT_PATH}
)
按需编辑plugintest.h和plugintest.cpp,这个就是该共享库项目的plugintest类了,我加入了一个int sum(int input1, int input2);公共函数,内容为:
int Plugintest::sum(int input1, int input2)
{
std::cout<<"Hello World!"<<std::endl;
int sum = input1+input2;
return sum;
}
保存并编译项目吧,没问题的话会在plugintest-build/lib目录里生成libplugintest.so。
2.2调用共享库的项目
2.2.1再次新建Cmake新建一个Qt Creator项目,用来调用刚刚生成的库
在项目根目录下新建一个plugintest文件夹,把生成的库和头文件include文件夹全复制进去
或者把库生成安装到计算机系统文件夹下,这样每次更新安装更加方便
2.2.2在CMakeLists.txt中添加如下代码
#-------------------------------------- 包含头文件 --------------------------------------
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/pludintest/include)
#-------------------------------------- 引入库文件 --------------------------------------
link_directories(${CMAKE_CURRENT_SOURCE_DIR}/pludintest)
#-------------------------------------- -添加项目- --------------------------------------
target_link_libraries(
${PROJECT_NAME}
${Qt5Widgets_LIBRARIES}
${Qt5Network_LIBRARIES}
libplugintest.so
)
2.2.3修改一下main.cpp调用pluginTest的sum()试试看吧
我的main.cpp内容如下:
#include <QApplication>
#include "plugintest.h"
int main(int argc, char* argv[])
{
QApplication a(argc, argv);
Plugintest demo;
int sum = demo.sum(3,5);
std::cout<<sum<<std::endl;
return a.exec();
}
2.2.4保存编译项目然后运行。
不出意外就会得到Hello World!和求和8的输出了,修改pluginTest项目的sum()函数重新编译该共享库,运行主程序就会得到不同的输出结果(不用重新编译主程序),这就是共享库(动态链接库)的好处所在。