要求

在当前项目中包含一个library库项目,并使用子项目的相关东西。

目录结构树

cmake_demo
├─ CMakeLists.txt
├─ domo.tree
├─ main.cpp
└─ sublibrary
   ├─ CMakeLists.txt
   ├─ sublibrary.cpp
   └─ sublibrary.h

过程

在main.cpp 中调用子目录内的sublibrary类内的东西,这样方便拓展,也方便迁移。比如sublibrary可直接拿到其他项目内调用。

代码

main 内的 CMakeLists.txt

cmake_minimum_required(VERSION 3.0.0)
project(cmake_demo VERSION 0.0.1 LANGUAGES CXX)

# 自动添加CMAKE_CURRENT_BINARY_DIR和CMAKE_CURRENT_SOURCE_DIR到当前处理的CMakeLists.txt
SET(CMAKE_INCLUDE_CURRENT_DIR ON)

# 添加子项目目录
add_subdirectory(sublibrary)

# 分别将h和cpp归至变量
FILE(GLOB SRC_HEADER "*.h")
FILE(GLOB SRC_SOURCE "*.cpp")

# 添加执行文件
add_executable(${PROJECT_NAME} ${SRC_HEADER} ${SRC_SOURCE})

# 自动包含目录
set_property(TARGET ${PROJECT_NAME} PROPERTY
    INTERFACE_INCLUDE_DIRECTORIES
    ${CMAKE_CURRENT_SOURCE_DIR}
)

# 链接子项目
target_link_libraries(${PROJECT_NAME} sublibrary)
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_BINARY_DIR})

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

sublibrary 内的CMakeLists.txt

cmake_minimum_required(VERSION 3.0.0)
project(sublibrary VERSION 0.0.1 LANGUAGES CXX)

# 自动添加CMAKE_CURRENT_BINARY_DIR和CMAKE_CURRENT_SOURCE_DIR到当前处理的CMakeLists.txt
SET(CMAKE_INCLUDE_CURRENT_DIR ON)

SET(BUILD_SHARED_LIBS ON)

# 分别将h和cpp归至变量
FILE(GLOB SRC_HEADER "*.h")
FILE(GLOB SRC_SOURCE "*.cpp")

# 添加库文件
add_library(${PROJECT_NAME} SHARED ${SRC_HEADER} ${SRC_SOURCE})

# 自动包含目录
set_property(TARGET ${PROJECT_NAME} PROPERTY
    INTERFACE_INCLUDE_DIRECTORIES
    ${CMAKE_CURRENT_SOURCE_DIR}
)

target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_CURRENT_BINARY_DIR})

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

本文由 管理员 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论