-
小型项目的组织
这一章,我们开始应用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()就是让模块更独立,模块之间解耦合。好处是程序设计具有层次感,模块将来更易被复用。
不仅仅着眼于当下,更要着眼未来。