1.生成动态库
在Windows下生成动态库,源码是和Linux有所区别,具体见之前文章;
直接看代码吧! my_lib_export.h
#pragma once
#ifdef MY_LIB_SHARED_BUILD
#ifdef _WIN32
#ifdef MY_LIB_EXPORTS
#define MY_LIB_API __declspec(dllexport)
#else
#define MY_LIB_API __declspec(dllimport)
#endif
#else
#define MY_LIB_API
#endif
#else
#define MY_LIB_API
#endif
my_lib.h
#pragma once
#include <iostream>
#include "my_lib_export.h"
class MY_LIB_API MyClass {
public:
static void MyPrint();
};
my_lib.cpp
#include "my_lib.h"
void MyClass::MyPrint() {
std::cout << "Hello from MyClass." << std::endl;
}
CMakeLists
cmake_minimum_required(VERSION 3.5)
project(hello_library)
#这里是自定义编译变量,通过在编译时给的值不同,来区分生成静态库还是动态库
option(BUILD_SHARED_LIBS "Specifies the type of libraries (SHARED or STATIC) to build" ON)
if (BUILD_SHARED_LIBS)
add_library(my_lib SHARED ${CMAKE_SOURCE_DIR}/my_lib/my_lib.cpp)
target_compile_definitions(my_lib PUBLIC -DMY_LIB_SHARED_BUILD)
target_compile_definitions(my_lib PRIVATE -DMY_LIB_EXPORTS)
else()
add_library(my_lib STATIC ${SrcFiles})
endif()
target_include_directories(my_lib
PUBLIC
${PROJECT_SOURCE_DIR}/my_lib
)
我这边使用的是QtCreator打开的CMakeLists.txt文件,后直接编译,会生成.lib和.dll文件
2.动态库的使用
包含以下文件:my_lib_export.h my_lib.h mian.cpp my_lib_export.h
#pragma once
#ifdef MY_LIB_SHARED_BUILD
#ifdef _WIN32
#ifdef MY_LIB_EXPORTS
#define MY_LIB_API __declspec(dllexport)
#else
#define MY_LIB_API __declspec(dllimport)
#endif
#else
#define MY_LIB_API
#endif
#else
#define MY_LIB_API
#endif
my_lib.h
#pragma once
#include <iostream>
#include "my_lib_export.h"
class MY_LIB_API MyClass {
public:
static void MyPrint();
};
main.cpp
#include "my_lib.h"
int main(int argc, char *argv[])
{
MyClass::MyPrint();
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(hello_library)
add_executable(cmake_examples_inst_bin
main.cpp
)
target_include_directories(cmake_examples_inst_bin
PUBLIC
${PROJECT_SOURCE_DIR}
)
target_link_libraries( cmake_examples_inst_bin
PRIVATE
my_lib
)
|