LoginSignup
54
55

More than 5 years have passed since last update.

CMake言語の基本構造

Last updated at Posted at 2014-11-30

はじめに

みなさん、こんにちは。CMake は、いろいろ使われているにもかかわらず、なぜか日本語の情報が少ないので、この Advent Clendar で言語仕様や Tips などを書いていこうかと思います。なお、対象となる CMake のバージョンは、基本的に現時点での最新の安定版、3.0.2 となります。

CMake言語の基本構造

まず、CMakeの言語仕様を知るために、公式ドキュメントの cmake-language という言語仕様について書いてあるページを見てみました。

すると、CMake言語は以下のような構造になっていることがわかりました。

file         ::=  file_element*
file_element ::=  command_invocation line_ending |
                  (bracket_comment|space)* line_ending
line_ending  ::=  line_comment? newline
space        ::=  <match '[ \t]+'>
newline      ::=  <match '\n'>

cmake-language(7) — CMake 3.0.2 Documentation, Source Files

command_invocation  ::=  space* identifier space* '(' arguments ')'
identifier          ::=  <match '[A-Za-z_][A-Za-z0-9_]*'>
arguments           ::=  argument? separated_arguments*
separated_arguments ::=  separation+ argument? |
                         separation* '(' arguments ')'
separation          ::=  space | line_ending

cmake-language(7) — CMake 3.0.2 Documentation, Command Invocations

これを見るとCMake言語は、すべてがコマンド呼び出しであることがわかります。これは、if()foreach()といった制御構文も同様です。endif()endforeach()についていた不自然な括弧は、この言語仕様のためだったのです。

コマンドの特徴

さて、CMake言語がコマンド呼び出しの羅列であることがわかったので、その中核のコマンドがどのような特徴を持っているのかにいて述べます。

コマンドに渡す引数の区切り文字は空白文字

コマンドに渡す引数の区切りは、空白文字となっていてカンマ,ではありません。

command(arg1 arg2 arg3) # OK
command(arg1,arg2,arg3) # NG; arg1,arg2,arg3 という一つの引数と解釈される

コマンド名は大文字小文字を区別しない

コマンド名は、大文字小文字を区別しません。以下はすべて同じコマンドを呼び出します。

message(arg)
MESSAGE(arg)
Message(arg)

コマンド名に使える文字は英数字とアンダースコア

function()コマンドとmacro()コマンドを使って独自のコマンドを定義することができますが、コマンド名に使えるのは英数字とアンダースコア(_)のみとなります。ただし、数字で始めることはできません(呼び出すときにエラーになります)。

# OK
function(my_command1)
  message(my_command1)
endfunction()
my_command1()

# OK
function(_my_command2)
  message(_my_command2)
endfunction()
_my_command2()

# NG
function(3_my_command)
  message(3_my_command)
endfunction()
3_my_command() # エラー

コマンドは戻り値がない

CMakeのコマンドには戻り値という概念がありません。なんらかの情報を呼び出し元に返したい場合は、格納する変数をコマンドの引数として渡すことになります。

string(TOUPPER hoge output_variable) # 文字列をすべて大文字にするコマンド
message(${output_variable}) # HOGE

おわりに

以上、CMake言語の基本構造とその中核であるコマンドについてでした。

明日は、mrk_21 さんの『CMake: コマンド引数の種類』です。

54
55
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
54
55