Briefly introduce how to use cmake (3) function

Get into the habit of writing together! This is the 11th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

We have used message to output the information output when cmake compiles before. Let's output the name of the project. The project name is stored in the variable PROJECT_NAME and we ${}can extract the variable value.

message("${PROJECT_NAME}")
复制代码

This will output the value of the variable that stores the item name, then ${variable} will extract the value of the variable, if the variable does not exist, this time it will output an empty string.

message("project name = ${PROJECT_NAME}")
复制代码

But this is not general enough, we can define the function print to output the variable name.

Next, use the function instruction to define a function, the first parameter is the function name, and the second parameter is the parameter

function(print var)
    message("${var} = ${${var}}")
endfunction()

print(PROJECT_NAME)
复制代码

${var}The parsing here is the variable name we passed in, so the first output ${var}output is PROJECT_NAME and then the PROJECT_NAME variable is fetched, so it ${${var}}is

We can also give only the function name without giving the parameter name when defining the function in the function instruction, and then we can obtain one or more parameters of the input function through some built-in variables (parameters).

parameter name illustrate
ARGN get parameter list
ARGC Get the number of parameters
ARGV get parameter value
PROJECT_NAME;MyVAR
复制代码
set(MyVAR "hello world")

function(print)
    message("${ARGN}")
endfunction()

print(PROJECT_NAME MyVAR)

复制代码
set(MyVAR "hello world")

function(print)
    message("${ARGN}")
    message("${ARGC}")
    message("${ARGV0}")
endfunction()

print(PROJECT_NAME MyVAR)
复制代码

PROJECT_NAME is a cmake own variable and a custom MyVAR with the value "hello world". When defining the function, we did not define any variables as formal parameters, because some built-in variables are provided for functions in cmake so that we can access the user input variables through these variables, so the advantage is that the number of variables is variable. When we pass in two variables.

PROJECT_NAME;MyVAR
2
PROJECT_NAME
复制代码

ARGN is a set of variable names, ARGC variable value is the number of input variables, and ARGV holds a list of all arguments given to the function

set(MyVAR "hello world")

function(print)
    message("${ARGN}")
    message("${ARGC}")
    foreach(var ${ARGN})
        message("${ARGV}==${${var}}")    
    endforeach()
endfunction()

print(PROJECT_NAME MyVAR)
复制代码

We can use the foreach statement to traverse the ARGN

Guess you like

Origin juejin.im/post/7085237413227790366