注意
本文最后更新于 2024-01-31,文中内容可能已过时。
一、 导言
导言
本篇内容目的和上一篇相似,但是出发点不同。我们计划是从文件中读取版本信息,而不是将其设置在CMakeLists.txt中。将版本保存在单独文件中的目的,是允许其他构建框架或开发工具使用独立于**CMake
的信息,而不需要将信息复制到多个文件中。**
二、项目结构
1
2
3
4
5
| .
├── CMakeLists.txt
├── example.cpp
├── version.hpp.in
└── VERSION.txt
|
https://gitee.com/jiangli01/tutorials/tree/master/cmake-tutorial/chapter6/03
三、相关源码
VERSION.txt
version.hpp.in
1
2
3
4
5
| #pragma once
#include <string>
const std::string PROGRAM_VERSION = "@PROGRAM_VERSION@";
|
example.cpp
1
2
3
4
5
6
7
8
9
| #include "version.hpp"
#include <iostream>
int main() {
std::cout << "This is output from code v" << PROGRAM_VERSION << std::endl;
std::cout << "Hello CMake world!" << std::endl;
}
|
CMakeLists.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
project(example LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/VERSION.txt")
file(READ "${CMAKE_CURRENT_SOURCE_DIR}/VERSION.txt" PROGRAM_VERSION)
string(STRIP "${PROGRAM_VERSION}" PROGRAM_VERSION)
else()
message(FATAL_ERROR "File ${CMAKE_CURRENT_SOURCE_DIR}/VERSION.txt not found")
endif()
configure_file(
version.hpp.in
generated/version.hpp
@ONLY
)
add_executable(example example.cpp)
target_include_directories(example
PRIVATE
${CMAKE_CURRENT_BINARY_DIR}/generated
)
|
引用
1
2
3
4
5
6
| if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/VERSION.txt")
file(READ "${CMAKE_CURRENT_SOURCE_DIR}/VERSION.txt" PROGRAM_VERSION)
string(STRIP "${PROGRAM_VERSION}" PROGRAM_VERSION)
else()
message(FATAL_ERROR "File ${CMAKE_CURRENT_SOURCE_DIR}/VERSION.txt not found")
endif()
|
首先,检查文件VERSION.txt
文件是否存在,如果不存在,则发出错误消息。如果存在,将内容读入PROGRAM_VERSION
变量中,该变量会去掉尾部的空格。
当设置了变量PROGRAM_VERSION
,就可以使用它来配置version.hpp.in
,生成generated/version.hpp:
1
2
3
4
5
| configure_file(
version.hpp.in
generated/version.hpp
@ONLY
)
|
四、结果展示
1
2
3
4
5
6
7
8
| $ mkdir -p build
$ cd build
$ cmake ..
$ cmake --build .
$ ./example
This is output from code v2.0.1-rc-2
Hello CMake world!
|
生成版本文件
version.hpp
1
2
3
4
5
| #pragma once
#include <string>
const std::string PROGRAM_VERSION = "2.0.1-rc-2";
|