cmake

Catalogue
  1. 1. 基础用法
  2. 2. 添加依赖
    1. 2.1. 添加外部目录链接
    2. 2.2. 添加外部依赖

基础用法

1
2
3
4
5
6
7
8
# 指定 cmake 的最低版本
cmake_minimum_required(VERSION 3.12)

# cmake 的项目名
project(hello)

# 定义可执行输出
add_executable(hello main.cpp)

添加依赖

1
2
3
4
5
6
7
8
9
10
11
cmake_minimum_required(VERSION 3.12)

project(hello)

# 增加依赖的子目录
add_subdirectory(poco)

add_executable(hello main.cpp)

# 给项目增加库链接
target_link_libraries(hello PUBLIC Poco::Foundation Poco::Zip Poco::Net Poco::Util) # replace `...` by all poco library you use

添加外部目录链接

因为外部项目并不在当前目录中,所以需要的一个参数,参考 cmake:用add_subdirectory()添加外部项目文件夹

1
2
3
4
5
6
7
8
cmake_minimum_required(VERSION 3.12)

project(hello)

add_subdirectory(/home/yanick/codes/misc/poco poco.out)

add_executable(hello main.cpp)
target_link_libraries(hello PUBLIC Poco::Foundation Poco::Zip Poco::Net Poco::Util) # replace `...` by all poco library you use

添加外部依赖

我们如果需要依赖一个 github 的 tar 包依赖需要这么完成。

  1. 定义需要导入的 cmake 文件,比如 gflag-2.2.2.cmake
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
include(ExternalProject)

set(GFLAG_ROOT ${CMAKE_BINARY_DIR}/thirdparty/gflag-2.2.2)
set(GFLAG_LIB_DIR ${GFLAG_ROOT}/lib)
set(GFLAG_INCLUDE_DIR ${GFLAG_ROOT}/include)

set(GFLAG_URL https://github.com/gflags/gflags/archive/v2.2.2.zip)
set(GFLAG_CONFIGURE cd ${GFLAG_ROOT}/src/gflag-2.2.2 && cmake -D CMAKE_INSTALL_PREFIX=${GFLAG_ROOT} .)
set(GFLAG_MAKE cd ${GFLAG_ROOT}/src/gflag-2.2.2 && make)
set(GFLAG_INSTALL cd ${GFLAG_ROOT}/src/gflag-2.2.2 && make install)
set(GFLAG_LIB ${GFLAG_LIB_DIR}/libgflags.a)

ExternalProject_Add(gflag-2.2.2
URL ${GFLAG_URL}
DOWNLOAD_NAME gflag-2.2.2.zip
PREFIX ${GFLAG_ROOT}
CONFIGURE_COMMAND ${GFLAG_CONFIGURE}
BUILD_COMMAND ${GFLAG_MAKE}
INSTALL_COMMAND ${GFLAG_INSTALL}
)
  1. 在主 CMakeLists.txt 中依赖
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    cmake_minimum_required(VERSION 3.5)

    project(hello)

    include(gflag-2.2.2.cmake)

    add_executable(hello main.cpp)
    # target_link_libraries(hello PUBLIC Poco::Foundation Poco::Zip Poco::Net Poco::Util) # replace `...` by all poco library you use


    target_link_libraries(hello ${GFLAG_LIB})
    target_include_directories(hello PRIVATE ${GFLAG_INCLUDE_DIR})