cmake--多级目录工程

Posted svenzhang9527

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cmake--多级目录工程相关的知识,希望对你有一定的参考价值。

前言

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

一, 目录结构

├── 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
)

以上是关于cmake--多级目录工程的主要内容,如果未能解决你的问题,请参考以下文章

cmake 多级CMakeLists.txt调用

cmake 构建工程

CMake (三)cmake 在工程中的用法

简易cmake多文件多目录工程模板

cmake编译Qt工程

cmake的外部编译