语法:cmake_minimum_required(VERSION versionNumber [FATAL_ERROR])
# CMake最小版本要求为2.8.3
cmake_minimum_required(VERSION 2.8.3)
语法:project(projectname [CXX] [C] [Java])
# 指定工程名为HELLOWORLD
project(HELLOWORLD)
project(HELLOWORLD LANGUAGES CXX C)
语法:set(VAR [VALUE] [CACHE TYPE DOCSTRING [FORCE]])
# 定义SRC变量,其值为main.cpp hello.cpp
set(SRC main.cpp hello.cpp)
语法:include_directories([AFTER|BEFORE] [SYSTEM] dir1 dir2 …)
# 将/usr/include/myincludefolder 和 ./include 添加到头文件搜索路径
include_directories(/usr/include/myincludefolder ./include)
语法:link_directories(dir1 dir2 …)
# 将/usr/lib/mylibfolder 和 ./lib 添加到库文件搜索路径
link_directories(/usr/lib/mylibfolder ./lib)
语法:add_library(libname [SHARED|STATIC|MODULE] [EXCLUDE_FROM_ALL] source1 source2 … sourceN)
# 通过变量 SRC 生成 libhello.so 共享库
add_library(hello SHARED ${SRC})
语法:add_compile_options()
# 添加编译参数 -Wall -std=c++11
add_compile_options(-Wall -std=c++11 -O2)
语法:add_library(exename source1 source2 … sourceN)
# 编译main.cpp生成可执行文件main
add_executable(main main.cpp)
语法:target_link_libraries(target library1library2…)
# 将hello动态库文件链接到可执行文件main
target_link_libraries(main hello)
语法:add_subdirectory(source_dir [binary_dir] [EXCLUDE_FROM_ALL])
# 添加src子目录,src中需有一个CMakeLists.txt
add_subdirectory(src)
语法:aux_source_directory(dir VARIABLE)
# 定义SRC变量,其值为当前目录下所有的源代码文件
aux_source_directory(. SRC)
# 编译SRC变量所代表的源代码文件,生成main可执行文件
add_executable(main ${SRC})
cmake 中的 message 命令就像是 C 语言中的 printf 函数,该命令可以将变量的值显示到终端。因此我们可以使用 message 命令查看变量值是否正确。但是,message 命令要比 printf 函数的功能强大,该命令可以终止编译系统的构建。而且这通常也是我们想要的效果。
语法:message([] “message text” …)
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:-1
CMake 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 …) 语句,终止编译系统的构建。
如果您要比较两个字符串(而不是变量),则只需将其引用为:
if("${A}" STREQUAL"some string")