CMake 学习笔记(子目录)

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 目录下也有头文件。

其实这个代码还可以改进,我们下一篇博客把这里的代码再优化一下。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值