这篇博客接着上篇。我们的目录结构和上一个例子完全相同。
CMakeLists.txt
MathFunctions
|- CMakeLists.txt
|- MathFunctions.cxx
|- MathFunctions.h
|- mysqrt.cxx
|- mysqrt.h
tutorial.cxx
TutorialConfig.h.in
在上一个例子中,为了包含 MathFunctions 库。我们在最上一层的 CMakeLists.txt 文件中加入了如下几行:
add_subdirectory(MathFunctions)
target_link_libraries(Tutorial PUBLIC MathFunctions)
target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
"${PROJECT_SOURCE_DIR}/MathFunctions"
)
我们希望把这里尽可能的简化。其中 target_include_directories() 是可以省略掉的。其实也不是省略掉,而是可以挪到子目录下的 CMakeLists.txt 中。
我们先看一下改进后的 MathFunctions 目录下的 CMakeList.txt。
add_library(MathFunctions MathFunctions.cxx)
target_include_directories(MathFunctions
INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
)
这里说一下, CMAKE_CURRENT_SOURCE_DIR 表示当前的源代码目录。
这样上层的 CMakeLists.txt 就只需要如下:
cmake_minimum_required(VERSION 3.10)
# set the project name and version
project(Tutorial VERSION 1.0)
# add the MathFunctions library
add_subdirectory(MathFunctions)
add_library(tutorial_compiler_flags INTERFACE)
target_compile_features(tutorial_compiler_flags INTERFACE cxx_std_11)
# configure a header file to pass some of the CMake settings
# to the source code
configure_file(TutorialConfig.h.in TutorialConfig.h)
# add the executable
add_executable(Tutorial tutorial.cxx)
# TODO 5: Link Tutorial to tutorial_compiler_flags
target_link_libraries(Tutorial PUBLIC MathFunctions)
# TODO 3: Remove use of EXTRA_INCLUDES
# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
)
上面代码有点长,其实为了引入 MathFunctions 只有
add_subdirectory(MathFunctions)
target_link_libraries(Tutorial PUBLIC MathFunctions tutorial_compiler_flags)
上面的代码里出现了 tutorial_compiler_flags, 这里也要解释几句。tutorial_compiler_flags 是什么呢?是个虚拟的库。
add_library(tutorial_compiler_flags INTERFACE)
target_compile_features(tutorial_compiler_flags INTERFACE cxx_std_11)
这两行的作用是代替下面的两行:
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
之所以要代替这两行,是因为这两行是全局的。对编译的每个文件都起作用。而 tutorial_compiler_flags 是局部的,只有
target_link_libraries(Tutorial PUBLIC MathFunctions tutorial_compiler_flags)
只有在编译 Tutorial 时会启用 cxx_std_11 这个 编译选项。