ILD

cmake第二课:language
作者:Yuan Jianpeng 邮箱:yuanjp89@163.com
发布时间:2025-6-5 站点:Inside Linux Development


CMake language包括:

comment,commands,variables


comments

注释以#开头


Variables

变量名是case sensitive,只能包含数字、字母和下划线。


cmake自动定义了很多变量,以CMAKE_开头。见下文:

https://cmake.org/cmake/help/latest/manual/cmake-variables.7.html


所有的变量都是string类型。


使用set命令来设置变量。

first argument是变量名

reset of arguments是变量的values。

多个value会拼成用分号分开的list,以string存储在变量中。


例子:

set(Foo "")      # 1 quoted arg -> value is ""
set(Foo a)       # 1 unquoted arg -> value is "a"
set(Foo "a b c") # 1 quoted arg -> value is "a b c"
set(Foo a b c)   # 3 unquoted args -> value is "a;b;c"


使用变量是:${VAR}

如果变量未定义,则为empty string。

使用变量如果不带引号,如果是list,则会扩展为多个参数。


例子:

set(Foo a b c)    # 3 unquoted args -> value is "a;b;c"
command(${Foo})   # unquoted arg replaced by a;b;c
                  # and expands to three arguments
command("${Foo}") # quoted arg value is "a;b;c"
set(Foo "")       # 1 quoted arg -> value is empty string
command(${Foo})   # unquoted arg replaced by empty string
                  # and expands to zero arguments
command("${Foo}") # quoted arg value is empty string


环境变量,可以通过这种方式访问:

$ENV{VAR}


Variable Scope

变量对当前CMakeLists文件、funciton,子目录的CMakeLists文件,使用include命令包含的文件,等都可见。

但是在子目录和子函数中,修改变量对父目录不可见。


使用set的PARENT_SCOPE选项,可以对父目录可见。

set(test 2 PARENT_SCOPE)

包含子目录和include文件的例子:

set(foo 1)

# process the dir1 subdirectory
add_subdirectory(dir1)

# include and process the commands in file1.cmake
include(file1.cmake)

set(bar 2)
# process the dir2 subdirectory
add_subdirectory(dir2)

# include and process the commands in file2.cmake
include(file2.cmake)


foo对下面的所有dir1,file1,dir2,file2可见。

bar只对dir2,file2可见。


Commands

命令:命令名,圆括号,空白字符分隔的参数


命令名大小写不敏感。


所有命令的列表:

https://cmake.org/cmake/help/latest/manual/cmake-commands.7.html


basic commands

set/unset,用来set unset variables

string, list, separate_arugments用来管理strings和lists

add_executable/add_library,用来添加可执行库目标和共享库目标。


Flow Control

包括3种:

conditional statements

looping constructs

procedure definitions


条件语句

if/else/elseif/endif


if (FOO)

else()

endif()


if (MSVC80)

elseif(MSVC90)

elseif (APPLE)

endif()


if的condition语句,见下面的链接:

https://cmake.org/cmake/help/latest/command/if.html


循环

foreach(name xx xx xx)

endforeach()


while(conditon)

endwhile()


procedure definitions

定义函数和宏


function(name arg1 arg2)

endfunction()


macro(name arg ...)

endmacro()


宏和函数不同的地方,是不会产生新的variable scope。



Copyright © linuxdev.cc 2017-2024. Some Rights Reserved.