cmake加载多个项目
时间: 2023-07-12 12:34:20 浏览: 101
在 CMake 中加载多个项目通常可以使用 `add_subdirectory()` 函数来实现。该函数用于告诉 CMake 加载另一个 CMakeLists.txt 文件,从而将另一个目录中的源代码文件和库文件添加到当前项目中。可以在当前项目的 CMakeLists.txt 文件中使用多个 `add_subdirectory()` 函数来加载多个项目。
例如,假设你有以下项目结构:
```
CMakeLists.txt
project/
CMakeLists.txt
source/
source_file.cpp
include/
header_file.h
library/
CMakeLists.txt
source/
library_source_file.cpp
include/
library_header_file.h
```
要在主项目中加载两个子项目,可以在主项目的 CMakeLists.txt 文件中添加以下代码:
```cmake
cmake_minimum_required(VERSION 3.10)
project(my_project)
add_subdirectory(project)
add_subdirectory(library)
```
这会告诉 CMake 加载 `project/CMakeLists.txt` 和 `library/CMakeLists.txt` 文件,并将它们添加到当前项目中。在子项目的 CMakeLists.txt 文件中,你可以定义源代码、库和可执行文件等内容。
```cmake
# project/CMakeLists.txt
add_library(my_project_library
source/source_file.cpp
)
target_include_directories(my_project_library
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
)
# library/CMakeLists.txt
add_library(my_library
source/library_source_file.cpp
)
target_include_directories(my_library
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
)
```
这样,你就可以在主项目中使用 `my_project_library` 和 `my_library` 两个库了。