In the previous blog we mentioned that each CMake project needs to include a CMakeLists.txt script. This script defines the target file (targets) and can do many other things, such as finding a third-party library, generating C + + header files, and so on. The CMake script has a lot of flexibility.
Whenever you integrate an external library and add support for other platforms in most cases, you need to edit the CMake script. I have spent a long time editing CMakeLists.txt without moving the CMake script-because the CMake script's documentation is very fragmented. But eventually I got the CMake script, and the purpose of this blog post is to get you to know the CMake script as quickly as I do.
This post does not cover all the CMake commands (hundreds of total!) ), but this is a fairly complete guide to the syntax and programming model of the CMake script.
Hello World
If you create a Hello.txt file that contains the following:
Message ("Hello world! ") # A message to print
You can run this file with Cmake-p hello.txt in the command line. (-p option tells CMake to run the specified script, but not build pipeline (build pipeline)) as expected, running this command outputs "Hello world! ”。
$ cmake-P Hello.txthello world!
All the variables are strings
In CMake, all variables are strings. You can use ${} in a string constant (string literal) to substitute a variable, which is referred to as a variable reference (variable reference). Modify the Hello.txt as follows:
Message ("Hello ${name}!") # Substitute a variable into the message
Now, if we define NAME with the-D option in the CMake command, Hello.txt will use this variable:
$ cmake-dname=newman-P Hello.txthello newman!
When a variable is not defined, the default value is an empty string:
$ cmake-P Hello.txthello!
We can also use the SET command to define variables in the script. The value of the variable when the first argument of set is a variable name, and the second argument:
Set (THING "Funk") message ("We want the ${thing}!")
The quotation marks in the set argument are optional, as long as there are no spaces or variable references in the string. For example, the set ("THING" Funk) and the command on the first line above are equivalent. For most cmake commands (except for the IF and while commands), the use of quotation marks is only a stylistic issue. When arguments are just variable names, I prefer not to use quotation marks.
Simulating data structures with prefixes (prefixes)
There is no concept of class (classes) in CMake, but you can simulate a data structure by defining a set of variables with the same prefix (prefixes). When used, you can use nested variable references (${}) to find intra-group variables. For example, the following script will output "John Smith lives at 123 Fake St." :
Set (john_name "John Smith") Set (john_address "123 Fake St")set (person "John")message ("${${person}_name} Lives at ${${person}_address}. ")
You can even use variable references in the SET command. For example, if the value of the person variable is still "John", the following code will place the value of the variable john_name as "John Goodman":
Set (${person}_name "John Goodman")
Each statement is a command
In CMake, each declaration is a command that receives a list of string parameters and has no return value . The parameters are separated by a space. As we have already seen, the SET command defines a variable in the file scope.
Another example is the math command that performs arithmetic operations in CMake. The first argument to the Math command must be EXPR, the second parameter is the name of the assigned variable, and the third argument is the evaluated expression, which is all three arguments. Note the following third line of code, CMake replace the value of the string my_sum before passing the argument to the Math command.
Math (EXPR my_sum "1 + 1") # Evaluate 1 + 1; store result in my_summessage ("The SUM is ${my_sum}." Math (EXPR double_sum "${my_sum} * 2") # Multiply by 2; store result in double_summessage ("DOUBLE so is ${do Uble_sum}. ")
Almost everything you need to do has a corresponding CMake command (https://cmake.org/cmake/help/latest/manual/cmake-commands.7.html). The string command helps you to perform advanced string operations such as regular expression substitution. The file command can read or write files or manipulate file system paths.
Control Flow Command
Even control flow statements are commands. The IF/ENDIF command allows you to execute a surrounded command based on conditions. Spaces in the control flow do not affect functionality, but usually the commands between the conditional commands are indented to improve readability. The following command checks whether the CMake built-in variable WIN is assigned:
If(WIN32) message ("You ' re running CMake on Windows." ) endif ()
CMake also has the while/endwhile command to repeat the command when the condition is true. The following loop will print all Fibonacci numbers below 1000000:
Set (a "1") Set (B "1") while(a less "1000000") message ("${a}") # Print A Math (EXPR T "${a} + ${ B} ") # ADD The numeric values of A and B; store result in T set (A" ${b} ") # Assign The value of B to A SE T (B "${t}") # Assign The value of T to Bendwhile ()
The use of if and while conditions in CMake differs from other programming languages. As shown above, to perform a numeric comparison, you must specify less as a string parameter. The following document (https://cmake.org/cmake/help/latest/command/if.html) explains in detail how to write conditional statements correctly.
If and while commands are special-if the specified variable is not surrounded by quotation marks, the IF and while will use the values of these variables directly. In the code above, I took advantage of this. The third line writes while (A less "1000000") instead of while (${a} "1000000"), although the two are equivalent. Other commands do not actively evaluate variables.
List (Lists) is a semicolon-delimited string
CMake has special substitution rules for parameters that do not use quotation marks. If the entire argument is a variable reference without quotation marks, and the value of the variable contains a semicolon, then CMake separates the argument at the semicolon and passes in the command containing the variable as multiple arguments. For example, the following code will pass three parameters to the math command:
Set (ARGS "EXPR"; T;1 + 1 ") Math (${args}) # equivalent to calling math (EXPR T" 1 + 1 ")
On the other hand, parameters surrounded by quotation marks are not separated by semicolons after they are replaced. CMake always passes the quote string as a separate parameter, preserving the integrity of the semicolon:
Set (ARGS "EXPR"; T;1 + 1 ") message (" ${args} ") # prints:expr; T;1 + 1
If more than two parameters are passed into the set command, they will be concatenated by semicolons and assigned to the specified variable. This is actually creating a list with parameters:
Set (My_list these is separate arguments) message ("${my_list}") # Prints:these;are;separate;arguments
You can use the list command to manipulate lists:
Set (My_list these is separate arguments) LIST (remove_item my_list "separate") # removes "separate" from the listm Essage ("${my_list}") # prints:these;are;arguments
The Foreach/endforeach command receives multiple parameters and iterates over parameters other than the first parameter:
foreach (ARG These is separate arguments) message ("${arg}") # Prints Each word on a separate lineendforeach ()
You can iterate a list by passing in an unquoted variable reference to foreach. Just like any other command, CMake separates the value of the variable with a semicolon:
foreach (ARG ${my_list}) # splits the LIST; passes items as arguments message ("${arg}") # Prints each I TEM on a separate Lineendforeach ()
function has scope;
In CMake, you can use the Function/endfunction command to define a function. The following code defines a function Doubleit that doubles the value of a parameter and prints:
function(Doubleit VALUE) math (EXPR RESULT "${value} * 2") message ("${result}") Endfunction () Doubleit ("4") # prints:8
The function runs in its own scope. Local variables defined in the function do not pollute the scope of the caller. If you want to return a value, you can pass in the variable you want to return, and then call the SET command with the special parameter parent_scope:
function(Doubleit VARNAME VALUE) math (EXPR RESULT "${value} * 2") set (${varname} "${result}" Parent_ Scope) # Set The named variable in caller's scopeendfunction () Doubleit (RESULT "4") # Tell the function
To set the variable named Resultmessage ("${result}") # prints:8
Similarly, the Macro/endmacro command can define a macro. However, unlike functions, macros and their callers work in the same scope. Therefore, all variables defined in the macro are set in the scope of the caller. We can replace the above functions with the following macros:
Macro (Doubleit VARNAME VALUE) math (EXPR ${varname} "${value} * 2") # Set the named variable in caller ' s scopeENDMA Cro () Doubleit (RESULT "4") # Tell the macro to set the variable named Resultmessage ("${result}") # prints:8
Both functions and macros can accept any number of arguments. Unnamed parameters are exposed to the function as a list by a special variable ARGN. The following function doubles all the received parameters and prints each parameter branch:
function(Doubleeach) foreach (ARG ${argn}) # Iterate over each argument math (EXPR N "${arg} * 2") # Double ARG ' s numeric value; Store result in N message ("${n}") # Print N Endforeach () endfunction () Doubleeach (5 6 7 8) # Prints, on separate lines
Include other scripts
CMake variables are defined in the file field. The include command executes other CMake scripts at the scope of the calling file . This is similar to the #include preprocessing commands in C + +. The include command is typically used to call other scripts to define some commonly used functions or macros, which use the values in the Cmake_module_path variable as the search path.
The find_package command searches for scripts that are shaped like find*.cmake and runs them in the same scope. These scripts are often used to help find external libraries. For example, if there is a file called Findsdl2.cmake in the search path, Find_package (SDL2) is equivalent to include (Findsdl2.cmake). (Note that this is just one of several uses of Find_package)
On the other hand, the Add_subdirectory command creates a new scope and then runs the CMakeLists.txt script under the specified folder in the new scope. This command is typically used to add another CMake subproject, such as a library or an executable file, to this project. If not specifically specified, the target files defined in the subproject are added to the build pipeline (pipeline). Variables in subproject scripts do not pollute the scope of this project-unless the Parent_scope option is used in the set command.
For example, in a turf (Https://github.com/preshing/turf) project, the following script is used when running CMake:
Reading and Setting properties
CMake uses add_executable, add_library, or Add_custom_target commands to define the target file. Once the target files are created, they have attributes (properties) that you can manipulate using the Get_property and Set_property commands. Unlike variables, target files are visible in all scopes, even if they are defined in a subproject. All properties of the destination file are also strings.
Add_executable (MyApp "main.cpp") # Create a target named myapp# Get the target ' s SOURCES property and assign it to Myapp_sourcesget_property (myapp_sources TARGET MYAPP property SOURCES) Message ("${myapp_sources}") # Prints: Main.cpp
Common target file attributes also include Link_libraries, Include_directories, and Compile_definitions. These properties are modified indirectly by the target_link_libraries, Target_include_directories, and target_compile_definitions commands. At the end of the script, CMake will use these target file attributes to build the build pipeline.
Other CMake entities (entities) also have their own properties. Each file scope has a collection of catalog properties (directory attributes). There is also a global properties collection that is visible to all scripts. Each C + + source file also has a source file Properties collection.
Original link: https://preshing.com/20170522/learn-cmakes-scripting-language-in-15-minutes/
15-Minute Learning CMake script (Translate)