前言
很多大工程由不同动态库和程序构成,并表现为多级目录和子工程的样式。
一, 目录结构
├── 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)
转载于:https://www.cnblogs.com/svenzhang9527/p/10704777.html
相关资源:cmake多目录工程实现