2025年cmake多级目录(cmake 多目录)

cmake多级目录(cmake 多目录)前言 很多大工程由不同动态库和程序构成 并表现为多级目录和子工程的样式 一 目录结构 CMakeLists txt nbsp gt 1 subbinary nbsp nbsp nbsp nbsp nbsp nbsp CMakeLists txt gt 2 nbsp nbsp nbsp nbsp nbsp nbsp main cpp



前言

很多大工程由不同动态库和程序构成,并表现为多级目录和子工程的样式。

一, 目录结构

├── CMakeLists.txt -------------------->[1]
├── subbinary
├── CMakeLists.txt----------->[2]
│ └── main.cpp
├── sublibrary1
├── CMakeLists.txt------------>[3]
│ ├── include
│ │ └── sublib1
│ │ └── sublib1.h
│ └── src
│ └── sublib1.cpp
└── sublibrary2
├── CMakeLists.txt------------>[4]
└── include
└── sublib2
└── sublib2.h

* link:CMakeLists.txt[] - Top level CMakeLists.txt
* link:subbinary/CMakeLists.txt[] - to make the executable
* link:subbinary/main.cpp[] - source for the executable
* link:sublibrary1/CMakeLists.txt[] - to make a static library
* link:sublibrary1/include/sublib1/sublib1.h[]
* link:sublibrary1/src/sublib2.cpp[]
* link:sublibrary2/CMakeLists.txt[] - to setup header only library
* link:sublibrary2/include/sublib2/sublib2.h[]

二,cmake脚本

├── CMakeLists.txt -------------------->[1]

cmake_minimum_required (VERSION 3.5)

project(subprojects)

# 添加子目录
add_subdirectory(sublibrary1)
add_subdirectory(sublibrary2)
add_subdirectory(subbinary)

├── CMakeLists.txt----------->[2]

project(subbinary)

# 创建可执行程序
add_executable(${PROJECT_NAME} main.cpp)

# 使用别名 sub::lib1 链接subproject1下的静态库
# 使用别名 sub::lib2 链接subproject2下的库文件
target_link_libraries(${PROJECT_NAME}
sub::lib1
sub::lib2
)

├── CMakeLists.txt------------>[3]

project (sublibrary1)

# 添加工程源文件到库,设置库别名

add_library(${PROJECT_NAME} src/sublib1.cpp)
add_library(sub::lib1 ALIAS ${PROJECT_NAME})

# 包含相关的头文件

target_include_directories( ${PROJECT_NAME}
PUBLIC ${PROJECT_SOURCE_DIR}/include
)

├── CMakeLists.txt------------>[4]

project (sublibrary2)

add_library(${PROJECT_NAME} INTERFACE)
add_library(sub::lib2 ALIAS ${PROJECT_NAME})

target_include_directories(${PROJECT_NAME}
INTERFACE
${PROJECT_SOURCE_DIR}/include
)

编程小号
上一篇 2026-03-03 23:46
下一篇 2026-03-03 23:17

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ri-ji/49684.html