Qter 发表于 2023-3-27 17:58:10

cmake:message 命令常用方式

我们在使用 cmake 构建工程的编译系统时,需要查看 CMakeLists.txt 中某些变量的值是否正确,尤其是遇到 CMake Error 时。但是 cmake 无法像编程语言一样进行单步调试。好在 cmake 中有 message 命令。cmake 中的 message 命令就像是 C 语言中的 printf 函数,该命令可以将变量的值显示到终端。因此我们可以使用 message 命令查看变量值是否正确。但是,message 命令要比 printf 函数的功能强大,该命令可以终止编译系统的构建。而且这通常也是我们想要的效果。1. 语法格式 message([<mode>] "message text" ...)
mode 的值包括 FATAL_ERROR、WARNING、AUTHOR_WARNING、STATUS、VERBOSE等。我主要使用其中的 2 个——FATAL_ERROR、STATUS。FATAL_ERROR:产生 CMake Error,会停止编译系统的构建过程;STATUS:最常用的命令,常用于查看变量值,类似于编程语言中的 DEBUG 级别信息。"message text"为显示在终端的内容。2. 例程比如,客户端和服务器通信时支持多种格式的消息,但是每次只能使用一种,并且在编译时确定。.├── CMakeLists.txt       主要的 CMakeLists.txt└── message    ├── 1m                消息大小为1M    │   ├── msg.cxx    │   └── msg.h    ├── 20m               消息大小为20M    │   ├── msg.cxx    │   └── msg.h    ├── 500k            消息大小为500K    │   ├── msg.cxx    │   └── msg.h    └── 5k                消息大小为5K      ├── msg.cxx      └── msg.h
CMakeLists.txt:cmake_minimum_required(VERSION 3.5)​project(test-message)​# MSG_SIZE 合法值set(MSG_SIZE_LIST 5k 500k 1m 20m)​#查询传入的 MSG_SIZE 值是否在 list 中list(FIND MSG_SIZE_LIST ${MSG_SIZE} RET)​message(STATUS "result:${RET}")​if(${RET} EQUAL -1)    #如果传入的参数不合法,那么就停止 cmake 程序    message(FATAL_ERROR "invalid msg size")endif()
测试命令:cmake -DMSG_SIZE=10m ..
执行结果:-- The C compiler identification is GNU 5.4.0-- The CXX compiler identification is GNU 5.4.0-- Detecting C compiler ABI info-- Detecting C compiler ABI info - done-- Check for working C compiler: /usr/bin/cc - skipped-- Detecting C compile features-- Detecting C compile features - done-- Detecting CXX compiler ABI info-- Detecting CXX compiler ABI info - done-- Check for working CXX compiler: /usr/bin/c++ - skipped-- Detecting CXX compile features-- Detecting CXX compile features - done-- result:-1CMake Error at CMakeLists.txt:12 (message):invalid msg size​​-- Configuring incomplete, errors occurred!See also "/home/sdc/project/msg/build/CMakeFiles/CMakeOutput.log".
由于传入的 MSG_SIZE 值非法,所以 CMakeLists.txt 中的 if 语句判断为真,执行 message(FATAL_ERROR ...) 语句,终止编译系统的构建。3. 官方说明https://cmake.org/cmake/help/la
页: [1]
查看完整版本: cmake:message 命令常用方式