添加依赖库和使用条件

CMakeLists.txt

  • 注意编译选项、生成配置文件和条件编译三部分的顺序
# 设置CMake版本最低要求
cmake_minimum_required(VERSION 3.10)

# 设置项目名称和版本
project(Tutorial VERSION 3.1)

# 指定 C++ 标准
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# 设置编译选项
option(USE_MYMATH "Use tutorial provided math implementation" ON)

# 生成一个头文件,传递 CMake 的一些设置到源代码
configure_file(TutorialConfig.h.in TutorialConfig.h)

# 添加 MathFunctions library
# add_subdirectory(MathFunctions)
if(USE_MYMATH)
  add_subdirectory(MathFunctions)
  list(APPEND EXTRA_LIBS MathFunctions)
  list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/MathFunctions")
endif()

# 添加源码文件和生成的目标文件的名称
add_executable(Tutorial main.cpp)

# target_link_libraries(Tutorial PUBLIC MathFunctions)
target_link_libraries(Tutorial PUBLIC ${EXTRA_LIBS})

# 添加头文件查找路径
# target_include_directories(Tutorial PUBLIC 
#                             "${PROJECT_BINARY_DIR}"
#                             "${PROJECT_SOURCE_DIR}/MathFunctions"
# )
target_include_directories(Tutorial PUBLIC 
                            "${PROJECT_BINARY_DIR}"
                            ${EXTRA_INCLUDES}
)

子模块(库)的 CMakeLists.txt 文件

add_library(MathFunctions mysqrt.cxx)

TutorialConfig.h.in

// 版本号配置信息
#define TUTORIAL_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define TUTORIAL_VERSION_MINOR @Tutorial_VERSION_MINOR@
// 程序中使用到的宏定义
#cmakedefine USE_MYMATH

程序中的宏定义使用

#ifdef USE_MYMATH
#include "MathFunctions.h"
#endif

... ...

#ifdef USE_MYMATH
    const double outputValue = mysqrt(inputValue);
#else
    const double outputValue = sqrt(inputValue);
#endif

添加库的使用需求

  1. 在子模块(库)的 CMakeLists.txt 文件末尾添加

    add_library(MathFunctions mysqrt.cxx)
    target_include_directories(MathFunctions INTERFACE 
                                ${CMAKE_CURRENT_SOURCE_DIR}
    )
    
    • INTERFACE means things that consumers require but the producer doesn’t
  2. 在上层 CMakeLists.txt 文件中就可以不添加 EXTRA_INCLUDES

    
    ... ...
    
    if(USE_MYMATH)
    add_subdirectory(MathFunctions)
    list(APPEND EXTRA_LIBS MathFunctions)
    # list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/MathFunctions")
    endif()
    
    ... ...
    
    
    target_include_directories(Tutorial PUBLIC 
                                "${PROJECT_BINARY_DIR}"
    )