cmakelists.txt 生成动态库
时间: 2023-10-02 11:05:27 浏览: 80
要在CMakeLists.txt中生成动态库,你需要添加以下内容:
```
add_library(mylibrary SHARED
src/Hello.cpp
)
```
这将创建一个名为mylibrary的动态库,并将src/Hello.cpp作为源文件进行编译。你可以根据需要添加其他源文件。确保在CMakeLists.txt中的适当位置添加这些命令。
#### 引用[.reference_title]
- *1* *2* [cmake--生成--动态库](https://blog.csdn.net/weixin_30291791/article/details/96956095)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
相关问题
CMakeLists.txt生成.so动态库
在 CMake 中生成动态库(.so)的步骤如下:
1. 在 CMakeLists.txt 文件中,使用 `add_library()` 函数来创建一个库目标。
```cmake
add_library(mylib SHARED mylib.cpp)
```
其中,`mylib` 是库的名称,`SHARED` 表示生成动态库。
2. 如果需要引用其他库,需要使用 `target_link_libraries()` 函数将这些库链接到当前库中。
```cmake
target_link_libraries(mylib lib1 lib2)
```
其中,`lib1` 和 `lib2` 是需要链接的库的名称。
3. 如果库中需要使用头文件,需要使用 `target_include_directories()` 函数将头文件目录添加到头文件搜索路径中。
```cmake
target_include_directories(mylib PUBLIC include)
```
其中,`include` 是头文件所在的目录。
4. 如果需要设置库的输出路径,可以使用 `set_target_properties()` 函数。
```cmake
set_target_properties(mylib PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/lib)
```
其中,`LIBRARY_OUTPUT_DIRECTORY` 表示库的输出路径,`${CMAKE_CURRENT_SOURCE_DIR}/lib` 表示当前 CMakeLists.txt 所在的目录下的 `lib` 子目录。
最终的 CMakeLists.txt 文件示例:
```cmake
cmake_minimum_required(VERSION 3.10)
project(mylib)
# 创建库目标
add_library(mylib SHARED mylib.cpp)
# 链接其他库
target_link_libraries(mylib PRIVATE lib1 lib2)
# 添加头文件搜索路径
target_include_directories(mylib PUBLIC include)
# 设置输出路径
set_target_properties(mylib PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/lib)
```
在运行 `cmake` 和 `make` 命令后,就可以在上述设置的输出路径中找到生成的动态库了。
CMakeLists.txt 添加动态库
在CMake中添加动态库的基本步骤通常包括创建目标库、指定编译器选项、定义链接库的接口以及设置导出的符号等。以下是一个简单的例子来说明如何在CMakeLists.txt文件中添加一个动态库:
```cmake
# 设置项目名称和版本号
project(MyDynamicLib VERSION 1.0)
# 创建动态库
add_library(MyDynamicLib SHARED
src/lib.cpp
src/lib.h
)
# 设置动态库的导出符号,通常用于生成和安装导入库
set_target_properties(MyDynamicLib PROPERTIES
VERSION "1.0"
SOVERSION "1"
)
# 配置动态库的安装路径,例如将库安装到系统库目录
install(TARGETS MyDynamicLib
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
RUNTIME DESTINATION bin
INCLUDES DESTINATION include
)
```
上述代码段定义了一个名为`MyDynamicLib`的动态库项目,包含了源文件`lib.cpp`和头文件`lib.h`。`add_library`命令用于创建动态库,并指定了`SHARED`关键字表示库为动态链接库。`set_target_properties`命令用于设置目标属性,其中`VERSION`和`SOVERSION`用于控制库的版本信息。最后,`install`命令指定了安装规则,`LIBRARY`、`ARCHIVE`和`RUNTIME`分别对应动态库、静态库和可执行文件的安装目标。
阅读全文
相关推荐















