使用cmake 编译代码 步骤:
1> mkdir build
2> cd build
3> build> cmake ..
4> build> cmake --build .
参考网址:
https://blog.csdn.net/fengzhongluoleidehua/article/details/79809756#comments
https://cmake.org/cmake/help/latest/guide/tutorial/index.html#adding-a-custom-command-and-generated-file-step-6
1, 最简单的工程CMakeLists.txt,把一个cpp编译成exe
cmake_minimum_required (VERSION 2.6)
project (Tutorial) // 设置工程名
add_executable(Tutorial tutorial.cpp) // 前者为目标文件名称,后面为源码
2,在CMakeLists.txt中定义程序版本号
2.1 修改CMakeLists.txt
cmake_minimum_required (VERSION 2.6)
project (Tutorial)
# 程序版本号
set (Tutorial_VERSION_MAJOR 1)
set (Tutorial_VERSION_MINOR 0)
# 配置一个头文件来接受来自CMake的设置信息,并在源码中使用
configure_file (
"${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
"${PROJECT_BINARY_DIR}/TutorialConfig.h"
)
# 保证能够找到上面CMake生成的头文件TutorialConfig.h
include_directories("${PROJECT_BINARY_DIR}")
# 生成exe可执行文件
add_executable(Tutorial tutorial.cpp)
2.2 然后创建一个.in 文件(TutorialConfig.h.in),如下:
# 此文件相当于一个中间件,CMake 填充,然后生成一个新的.h 文件
#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
2.3 源码中可以直接include TutorialConfig.h 头文件进行使用
3, 使用库
3.1 编译库:
编译源码为一个库使用一下参数:
add_library(MathFunctions mysqrt.cxx) //CMakeLists.txt 中仅需此一行即可完成
该配置编译后,会产生一个静态的lib,以及对应的pdb文件
3.2 使用库
要使用库中提供的函数,需要在外层CMakeLists.txt 中,使用如下代码:
cmake_minimum_required (VERSION 2.6)
project (First02)
include_directories("${PROJECT_SOURCE_DIR}/02/")// 需要找到函数的声明
add_subdirectory(02) // 保证这个库能被编译到,必须在子目录下
add_executable (target main.cpp)
target_link_libraries(target MyLib) // 链接到这个库,前者必须为目标文件名
3.3 配置库文件为可选库
# should we use our own math functions?
option (USE_MYMATH "Use tutorial provided math implementation" ON) 这个配置在GUI中显示,并且默认ON
if (USE_MYMATH)
include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
add_subdirectory (MathFunctions)
set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)
endif (USE_MYMATH)
# add the executable
add_executable (Tutorial tutorial.cxx)
target_link_libraries (Tutorial ${EXTRA_LIBS})
EXTRA_LIBS”变量是用来收集每一个可选库的,以便他们链接到可执行程序中.这是一个保持大项目工程可选库清洁的通用方法.相应的源代码修改是很直观的,如下:
源代码中可以这样使用:
#ifdef USE_MYMATH
double outputValue = mysqrt(inputValue);
#else
double outputValue = sqrt(inputValue);
#endif
CMake通过修改配置文件TutorialConfig.h.in配置文件来为源文件这个提供支持,添加内容如下:
#cmakedefine USE_MYMATH