9/5 cmake初步学习 Tutorial step1 and step2
cmake官方文件第一步:
https://cmake.org/cmake/help/latest/guide/tutorial/A%20Basic%20Starting%20Point.html
一个简单的开方程序用cmake来组织:
CMakeLists:
cmake_minimum_required(VERSION 3.10)
# set the project name
project(Tutorial VERSION 1.0)
set (Tutorial_VERSION_MAJOR 1)
set (Tutorial_VERSION_MINOR 0)
configure_file (
"${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"#根据.h.in生成.h文件
"${PROJECT_BINARY_DIR}/TutorialConfig.h"
)
include_directories("${PROJECT_BINARY_DIR}")#预处理需要的目录(要用的代码的目录)
# add the executable
add_executable(Tutorial tutorial.cpp)
TutorialConfig.h.in:
#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
执行的指令是
mkdir build
cmake ..
cmake --build .
注意生成的TutorialConfig.h是在build下,用TutorialConfig.h.in做模板生成的。
第二步:
https://cmake.org/cmake/help/latest/guide/tutorial/Adding%20a%20Library.html
https://juejin.cn/post/6844903557196414989
把sqrt函数用自己的函数实现,并把函数打包。
CMakeLists.txt
# step2
add_library(MathFunctions mysqrt.cxx)
主CMakeLists增加:
include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")# 包含子目录的源文件
add_subdirectory (MathFunctions) # 调用子目录的CMakeLists
# add the executable
add_executable (Tutorial tutorial.cpp)
target_link_libraries (Tutorial MathFunctions)# 链接库文件
再增加开关,控制是否使用自己的库
TutorialConfig.h.in增加
#cmakedefine USE_MYMATH
cmakedefine 会被替换成 define,改为define也可以。
主目录下的CMakeLists修改:
cmake_minimum_required(VERSION 3.10)
# set the project name
project(Tutorial VERSION 1.0)
set (Tutorial_VERSION_MAJOR 1)
set (Tutorial_VERSION_MINOR 0)
configure_file (
"${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
"${PROJECT_BINARY_DIR}/TutorialConfig.h"
)
include_directories("${PROJECT_BINARY_DIR}")
# include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
# add_subdirectory (MathFunctions)
# add the executable
# add_executable (Tutorial tutorial.cpp)
# target_link_libraries (Tutorial MathFunctions)
option (USE_MYMATH
"Use tutorial provided math implementation" ON)
if (USE_MYMATH)
include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
add_subdirectory (MathFunctions)
set (EXTRA_LIBS MathFunctions)# 字符串可以加引号,也可以不加
endif (USE_MYMATH)# endif要接表达式
# add the executable
add_executable (Tutorial tutorial.cpp)
target_link_libraries (Tutorial ${EXTRA_LIBS})
option:提供一个选项供用户选择为 ON 或 OFF。如果没有提供初始值,则使用 OFF。
浙公网安备 33010602011771号