使用动态库发布的一个好处是,如果只是更新了接口的内部实现,可以直接替换动态库而不需要像静态库一样加入到编译环境重新链接
CMakeLists.txt
cmake_minimum_required(VERSION 3.17)
project(dtest)
include(GenerateExportHeader)
add_library(dtest SHARED dynamic_test.cxx)
generate_export_header(
dtest
)
target_include_directories(dtest PRIVATE ${CMAKE_BINARY_DIR})
target_compile_definitions(dtest PRIVATE "dtest_EXPORTS")
#install
install(FILES ${CMAKE_BINARY_DIR}/dtest_export.h
${CMAKE_SOURCE_DIR}/dynamic_test.hxx DESTINATION include
)
install(TARGETS dtest DESTINATION lib)
dtest_export.h
CMake工具输出的文件,需要定义dtest_EXPORTS
#ifndef DTEST_EXPORT_H
#define DTEST_EXPORT_H
#ifdef DTEST_STATIC_DEFINE
# define DTEST_EXPORT
# define DTEST_NO_EXPORT
#else
# ifndef DTEST_EXPORT
# ifdef dtest_EXPORTS
/* We are building this library */
# define DTEST_EXPORT __declspec(dllexport)
# else
/* We are using this library */
# define DTEST_EXPORT __declspec(dllimport)
# endif
# endif
# ifndef DTEST_NO_EXPORT
# define DTEST_NO_EXPORT
# endif
#endif
#ifndef DTEST_DEPRECATED
# define DTEST_DEPRECATED __declspec(deprecated)
#endif
#ifndef DTEST_DEPRECATED_EXPORT
# define DTEST_DEPRECATED_EXPORT DTEST_EXPORT DTEST_DEPRECATED
#endif
#ifndef DTEST_DEPRECATED_NO_EXPORT
# define DTEST_DEPRECATED_NO_EXPORT DTEST_NO_EXPORT DTEST_DEPRECATED
#endif
#if 0 /* DEFINE_NO_DEPRECATED */
# ifndef DTEST_NO_DEPRECATED
# define DTEST_NO_DEPRECATED
# endif
#endif
#endif /* DTEST_EXPORT_H */
dynamic_test.hxx
#pragma once
#include "dtest_export.h"
DTEST_EXPORT void print();
dynamic_test.cxx
#include "dynamic_test.hxx"
#include <iostream>
using namespace std;
void print(){
// cout<<"hello v1"<<endl;
cout<<"hello v2"<<endl;
cout<<"hello v2"<<endl;
}
好处就是,一旦我们将头文件和lib给程序进行链接,只要我们改动print里面的实现,以后就可以只把动态库给对方就可以了