1 创建链接库
使用简单的一个函数来实现链接库功能,函数实现如下:
library.cpp文件:
#include "library.h"
#include <iostream>
void hello() {
std::cout << "Hello, library World!" << std::endl;
}
library.h文件:
#ifndef LIB_PUBLISHER_LIBRARY_H
#define LIB_PUBLISHER_LIBRARY_H
void hello();
#endif //LIB_PUBLISHER_LIBRARY_H
链接库生成的CMakeLists文件:
cmake_minimum_required(VERSION 2.8)
project(lib_publisher)
set(CMAKE_CXX_STANDARD 11)
SET (LIB_PUBLISHER_SRC library.cpp library.h)
add_library(lib_publisher SHARED ${LIB_PUBLISHER_SRC})
ADD_LIBRARY (lib_publisher_static STATIC ${LIB_PUBLISHER_SRC})
INSTALL (TARGETS lib_publisher lib_publisher_static LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib)
INSTALL (FILES library.h DESTINATION include/library)
将链接库生成动态和静态两种链接库,并安装到系统的指定位置(/usr/local/bin与/usr/local/include)。
2 在项目中使用动态链接库
CMakeLists文件:
cmake_minimum_required(VERSION 2.8)
project(ExoSSimulator)
add_definitions(-std=c++11)
set(CMAKE_CXX_STANDARD 11)
find_library(
pub
lib_publisher
)
add_executable(simulator main.cpp src/communication/Server.cpp src/utilities/unchararray_utility.cpp include/Server.h include/wraper.h include/unchararray_utility.h)
target_link_libraries(simulator ${pub})
其中lib_publisher为在1中动态链接库中生成的名称。
在工程中直接引入.h文件#include "library/library.h"
,
并调用hello()
。
结果如下: