1. 程式人生 >實用技巧 >其它 >windows--cmake與c++的使用教程(16)

windows--cmake與c++的使用教程(16)


1 概述

本節目標: macro編寫與函式編寫

2 macro 與 function

  • 可類比C語言中的巨集定義與函式
  • CMake function傳遞引數時,不用傳遞引數型別
  • cmake macro巨集只是對字串的簡單替換。和define類似。

3 macro 語法

  • macro需 與 endmacro配對使用
macro(<name> [<arg1> ...])
  <commands>
endmacro()

5 function 語法

  • function需與endfunction配對使用,
  • function可結合return()使用, 也就是說, 函式體可以寫 return()
function(<name> [<arg1> ...])
  <commands>
endfunction()

6 一個例子幫助理解macro和function的區別

6.1 cmake腳背

set(var_demo "ABC")

# 巨集定義
macro(macro_demo arg)
  message("arg = ${arg}")
  set(arg "123")
  message("# after change the value of arg.")
  message("arg = ${arg}")
endmacro()

message("")
message("=== call macro ===")
macro_demo(${var_demo})
message("")
message("")

# 函式定義
function(func_demo arg)
  message("arg = ${arg}")
  set(arg "123")
  message("# after change the value of arg.")
  message("arg = ${arg}")
endfunction()

message("")
message("=== call function ===")
func_demo(${var_demo})
message("")
message("")
message("")

6.2 輸出結果

=== call macro ===
arg = ABC
# after change the value of arg.
arg = ABC



=== call function ===
arg = ABC
# after change the value of arg.
arg = 123

7 function 中使用return

  • 類似C語言函式return語句。

7.1 一個例子

function(func_demo_return )
    message("11111")
    return()
    message("22222")
endfunction(func_demo_return )

func_demo_return()

7.2 輸出結果

11111

因為執行了return(), 所以不會輸出 22222