CMake 中文简易手册

最基本的项目是从源代码文件构建的可执行文件。对于简单的项目,只需要三行代码。

cmake_minimum_required(VERSION 3.10)

# set the project name
project(Tutorial)

# add the executable
add_executable(Tutorial tutorial.cxx)

如果想要将子工程构建为动态链接库后用于本工程,需要进行一下操作:

以下面的文件树为例:
在这里插入图片描述
CMakeTutorial 文件夹下的 CMakeList.txt 内容如下:

# set the minimum required version of cmake for a project
cmake_minimum_required(VERSION 3.14)

# set the project name and version
project(CMakeTutorial VERSION 1.3.0.0)

# specify the C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# provide an option "USE_USER_TOOLS" for the user to select as True or False
set(USE_USER_TOOLS True)

# provide an option "USE_EXISTIONG_USER_TOOLS" for the user to select as True or False
set(USE_EXISTIONG_USER_TOOLS False)

if(${USE_USER_TOOLS})
    if(${USE_EXISTIONG_USER_TOOLS})
        message("Use author provided existing tools implementation")
        # appends elements to the list "EXTRA_LIBS"
        list(APPEND EXTRA_LIBS libtools)
        # appends elements to the list "EXTRA_INCLUDES"
        list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/tools")
        ## copy library to the binary tree
        file(COPY ${PROJECT_BINARY_DIR}/tools/libtools.dll DESTINATION ${PROJECT_SOURCE_DIR}/tools/)
    else()
        message("Use author provided tools implementation")
        # add a subdirectory to the build
        add_subdirectory(tools)
        # appends elements to the list "EXTRA_LIBS"
        list(APPEND EXTRA_LIBS tools)
        # appends elements to the list "EXTRA_INCLUDES"
        list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/tools")
    endif()
endif()

# configure a header file to pass some of the CMake settings to the source code
configure_file (
        "${PROJECT_SOURCE_DIR}/config.h.in"
        "${PROJECT_BINARY_DIR}/config.h"
        )

# find all source files in a directory.
aux_source_directory(. SRCS_LIST)

# add the executable
add_executable(CMakeTutorial ${SRCS_LIST})

# specify the paths in which the linker should search for libraries when linking a given target
target_link_directories(CMakeTutorial PUBLIC ${EXTRA_INCLUDES})

# link libraries to target
target_link_libraries(CMakeTutorial PUBLIC ${EXTRA_LIBS})

# specifies include directories to use when compiling a given target
# add the binary tree to the search path for include files
# so that we will find config.h and source
target_include_directories(CMakeTutorial PUBLIC
        ${PROJECT_SOURCE_DIR}
        ${PROJECT_BINARY_DIR}
        ${EXTRA_INCLUDES}
        )

tools 文件夹下的 CMakeList.txt

aux_source_directory(. TOOL_LIB_SRCS_LIST)
add_library(tools SHARED ${TOOL_LIB_SRCS_LIST})
target_include_directories(tools
        INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
        )

构建后结果
在这里插入图片描述

如果编译子目录工程之后,不需要在修改,那么可以将动态库连接语句改为:

# provide an option "USE_EXISTIONG_USER_TOOLS" for the user to select as True or False
set(USE_EXISTIONG_USER_TOOLS True)

猜你喜欢

转载自blog.csdn.net/Flame_alone/article/details/105928926