《CMake 进阶之路》第二章 添加一个库 add_library()的常规用途

  • 小型项目的组织

这一章,我们开始应用CMake进行项目组织,正式开发过程中涉及到项目的分层组织,项目的模块之间可以通过Library这种方式进行封装。

说明:本文例子引用了cmake.org的tutorial部分代码

下面是本章的文件的目录结构

可以看到在Top Level文件夹下创建了一个MathFunctions文件夹,里面也有一个CMakeLists.txt, 在里面我们添加这样一行代码

add_library(MathFunctions mysqrt.cpp)

在TopLevel的CMakeLists.exe里面

#原始代码 ##########################################
# add the MathFunctions library
add_subdirectory(MathFunctions)

# add the executable
add_executable(Lesson02 main.cpp)

target_link_libraries(Lesson02 PUBLIC MathFunctions)

# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
target_include_directories(Lesson02 PUBLIC
                          "${PROJECT_BINARY_DIR}"
                          "${PROJECT_SOURCE_DIR}/MathFunctions"
                          )


#进化后 #################################################
if(USE_MYMATH)
  add_subdirectory(MathFunctions)
  list(APPEND EXTRA_LIBS MathFunctions)
  list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/MathFunctions")
endif()

# add the executable
add_executable(Lesson02 main.cpp)

target_link_libraries(Lesson02 PUBLIC ${EXTRA_LIBS})

# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
target_include_directories(Lesson02 PUBLIC
                           "${PROJECT_BINARY_DIR}"
                           ${EXTRA_INCLUDES}
                           )

添加Config File

option(USE_MYMATH "Use tutorial provided math implementation" ON)

# configure a header file to pass some of the CMake settings
# to the source code
configure_file(TutorialConfig.h.in TutorialConfig.h)

在TopLevel目录下创建build文件夹,首先输入cmake ..命令,

cmake ..

然后用tree . 查看生成的内容,可以看到在MathFunctions文件夹下面也创建了同样的CMakeFiles文件夹,Makefile,里面包含了所需的makefile文件

然后在TopLevel目录下,输入:

make

#再输入: tree .

截取make过程可以看到

可以看出来make过程:编译生成.o文件,然后链接生成.a文件,最后生成可执行文件。

可以看到make之后的文件数增加了,多了*.o文件和*.a,其中libMathFunctions.a就是作为Library文件被上层调用。

总结:add_library()就是让模块更独立,模块之间解耦合。好处是程序设计具有层次感,模块将来更易被复用。

不仅仅着眼于当下,更要着眼未来。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值