CMake 学习笔记(子目录)
稍微大一点的软件项目都会包含好几个部分。我们会根据功能或者其他划分方法,把代码放到不同的子目录下。有些子目录下的代码要编译成库文件,我们的主程序调用这些库。下面就来讲讲这种如何在 cmake 中实现。
这个例子有如下的文件组成:
CMakeLists.txt
MathFunctions
|- CMakeLists.txt
|- MathFunctions.cxx
|- MathFunctions.h
|- mysqrt.cxx
|- mysqrt.h
tutorial.cxx
TutorialConfig.h.in
MathFunctions 是个子目录,里面的文件会编译成一个库,这个库的名字就叫做 MathFunctions。
我们先来看 MathFunctions/CMakeLists.txt 文件
# TODO 1: Add a library called MathFunctions with sources MathFunctions.cxx
# and mysqrt.cxx
# Hint: You will need the add_library command
add_library(MathFunctions MathFunctions.cxx mysqrt.cxx)
可以看到里面的代码很简单,就是生成一个名字叫 MathFunctions 的库。
然后再看看上一级目录中的 CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(Tutorial VERSION 1.0)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
configure_file(TutorialConfig.h.in TutorialConfig.h)
# add the executable
add_executable(Tutorial tutorial.cxx)
add_subdirectory(MathFunctions)
target_link_libraries(Tutorial PUBLIC MathFunctions)
target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
"${PROJECT_SOURCE_DIR}/MathFunctions"
)
target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
)
这里面新添加的代码其实就只有几行,我们把这几行单独拿出来。
add_subdirectory(MathFunctions)
target_link_libraries(Tutorial PUBLIC MathFunctions)
target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
"${PROJECT_SOURCE_DIR}/MathFunctions"
)
add_subdirectory(MathFunctions) 告诉cmake 去 MathFunctions 目录下找 CMakeLIsts.txt 。
target_link_libraries(Tutorial PUBLIC MathFunctions) 将 MathFunctions 链接到我们的可执行文件。
target_include_directories 告诉编译器 MathFunctions 目录下也有头文件。
其实这个代码还可以改进,我们下一篇博客把这里的代码再优化一下。