1. 程式人生 > >10-cmake語法-函數和宏的定義

10-cmake語法-函數和宏的定義

ase ons d+ div PV upd ... enc defined

cmake語法不僅僅可以適用於 CMakeLists.txt,也適用於 xxx.cmake 文檔。

OpenCV CMakeLists.txt 中,很多 ocv_XXX() 的函數,都是定義在相應的 xxx.cmake 中。

比如:L116

include(cmake/OpenCVUtils.cmake)

# must go before the project command

# @ 解說:
# @ ocv_update 函數定義在 cmake/OpenCVUtils.cmake 這個組件中,可以用Notepad++打開看看。
ocv_update(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "Configs" FORCE)
if(DEFINED CMAKE_BUILD_TYPE)
  set_property( CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS ${CMAKE_CONFIGURATION_TYPES} )
endif()

  

函數定義:

function(函數名 參數名)

  ...

endfunction()

例子:cmake/OpenCVMinDepVersions.cmake中

function(ocv_cmake_eval var_name)
  if(DEFINED ${var_name})
    file(WRITE "${CMAKE_BINARY_DIR}/CMakeCommand-${var_name}.cmake" ${${var_name}})
    include("${CMAKE_BINARY_DIR}/CMakeCommand-${var_name}.cmake")
  endif()
  if(";${ARGN};" MATCHES ";ONCE;")
    unset(${var_name} CACHE)
  endif()
endfunction()

  

宏的定義:

macro(宏名 參數)
  ...
endmacro()

例子:cmake/OpenCVMinDepVersions.cmake中

macro(ocv_cmake_configure file_name var_name)
  configure_file(${file_name} "${CMAKE_BINARY_DIR}/CMakeConfig-${var_name}.cmake" ${ARGN})
  file(READ "${CMAKE_BINARY_DIR}/CMakeConfig-${var_name}.cmake" ${var_name})
endmacro()

  

函數和宏不支持return,需要傳參出去,可以通過形參輸入傳出。

macro(ocv_xxx return_hello_world)
  set(return_hello_world "Hello_World")
endmacro()

  

參考:

https://www.jianshu.com/p/44ba033c262a

10-cmake語法-函數和宏的定義