使用動態庫發布的一個好處是,如果只是更新了接口的內部實現,可以直接替換動態庫而不需要像靜態庫一樣加入到編譯環境重新鏈接
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里面的實現,以后就可以只把動態庫給對方就可以了
