字符串

cmake 中所有变量都是字符串.

查找与替换

查找:

set(NAME "Tasha Wang")
string(FIND ${NAME} " " LAST_NAME)
message("Last name: ${LAST_NAME}")

替换:

set(KERNEL_VERSION 5.4.2)
string(REPLACE "5." "4." OLD_VERSION ${KERNEL_VERSION})
message("OLD version ${OLD_VERSION}")

字符串操作方法

合并:

set(MAJOR_VERSION 5)
set(MINOR_VERSION 4)
set(PATCH_VERSION 2)
string(CONCAT VERSION_NUMBER ${MAJOR_VERSION} ${MINOR_VERSION} ${PATCH_VERSION})
message("KERNEL_VERSION: ${VERSION_NUMBER}")

拼接字符串:

set(APT_PARTS "/etc" "apt" "sources.list")
string(JOIN "/" APT_PATH ${APT_PARTS})
message("APT config path: ${APT_PATH}")

移除两端的空白字符:

set(USERNAME "Tasha Wang ")
string(STRIP ${USERNAME} USERNAME)
message("Username::${USERNAME}::")

比较字符串:

string(COMPARE EQUAL ${CMAKE_BUILD_TYPE} "Release" IS_RELEASE)
message("is release mode: ${IS_RELEASE}")

正则表达式

替换:

set(KERNEL_VERSION "5.4.2")
string(REGEX REPLACE "[0-9]$" "0" NEW_VERSION ${KERNEL_VERSION})
message("NEW version: ${NEW_VERSION}")

Hash 计算

set(NAME "Tasha Wang")
string(SHA256 NAME_HASH NAME)
message("hash of name: ${NAME_HASH}")

生成字符串

支持生成时间标签, UUID, 随机字符串等等.

string(RANDOM LENGTH 8 RANDOM_PASSWORD)
message("RANDOM_USER: ${RANDOM_PASSWORD}")

参考

CMake String 手册