cmake_minimum_required(VERSION3.15)# set the project name
project(Tutorial)SET(SRC_LISTtutorial.cpp)# add the executable
add_executable(${PROJECT_NAME}${SRC_LIST})
这里注意到 CMake 语法似乎习惯性的大写变量的所有字母。
接下来是两个新的指令
1
2
3
4
5
6
7
8
9
10
11
12
13
14
cmake_minimum_required(VERSION3.15)# set the project name and version
project(TutorialVERSION1.0.2)configure_file(TutorialConfig.h.inTutorialConfig.h)set(SRC_LISTtutorial.cpp)# add the executable
add_executable(${PROJECT_NAME}${SRC_LIST})target_include_directories(${PROJECT_NAME}PUBLIC${PROJECT_BINARY_DIR})
// TutorialConfig.h
// the configured options and settings for Tutorial
#define Tutorial_VERSION_MAJOR 1
#define Tutorial_VERSION_MINOR 0
#define Tutorial_VERSION_PATCH 2
接着就可以直接在 tutorial.cpp 里去 include 这个 TutorialConfig.h 了,like so
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// tutorial.cpp
#include<iostream>#include<TutorialConfig.h>intmain(intargc,char*argv[]){if(argc<2){// report version
std::cout<<argv[0]<<" Version "<<Tutorial_VERSION_MAJOR<<"."<<Tutorial_VERSION_MINOR<<std::endl;std::cout<<"Usage: "<<argv[0]<<" number"<<std::endl;return1;}}
构建运行后的结果:
1
2
3
PS D:\Dev\CMakeStudy\Demo\build> .\Debug\Tutorial.exe
D:\Dev\CMakeStudy\Demo\build\Debug\Tutorial.exe Version 1.0
Usage: D:\Dev\CMakeStudy\Demo\build\Debug\Tutorial.exe number
类似的,也可以给编译时间打上时间戳
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
cmake_minimum_required(VERSION3.15)# set the project name and version
project(TutorialVERSION1.0.2)string(TIMESTAMPCOMPILE_TIME%Y%m%d-%H%M%S)configure_file(TutorialConfig.h.inTutorialConfig.h)set(SRC_LISTtutorial.cpp)# add the executable
add_executable(${PROJECT_NAME}${SRC_LIST})target_include_directories(${PROJECT_NAME}PUBLIC${PROJECT_BINARY_DIR})
// the configured options and settings for Tutorial
#define Tutorial_VERSION_MAJOR @PROJECT_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @PROJECT_VERSION_MINOR@
#define Tutorial_VERSION_PATCH @PROJECT_VERSION_PATCH@
#define TIMESTAMP @COMPILE_TIME@
cmake build 生成的 TutorialConfig.h 会增加一个时间宏
1
2
3
4
5
6
// the configured options and settings for Tutorial
#define Tutorial_VERSION_MAJOR 1
#define Tutorial_VERSION_MINOR 0
#define Tutorial_VERSION_PATCH 2
#define TIMESTAMP 20241223-022712
然后就可以在代码里调用了。
如果需要指定 C++ 标准的话,可以在 CMakeLists 里加上这两个指令
1
2
3
4
5
6
7
8
cmake_minimum_required(VERSION3.15)# set the project name and version
project(${PROJECT_NAME}VERSION1.0)# specify the C++ standard
set(CMAKE_CXX_STANDARD11)set(CMAKE_CXX_STANDARD_REQUIREDTrue)
# add the MathFunctions library
add_subdirectory(MathFunctions)# add the executable
add_executable(${PROJECT_NAME}tutorial.cpp)target_link_libraries(${PROJECT_NAME}PUBLICMathFunctions)# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
target_include_directories(${PROJECT_NAME}PUBLIC${PROJECT_BINARY_DIR}${PROJECT_SOURCE_DIR}/MathFunctions)