FindMatlab.cmake 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file Copyright.txt or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. FindMatlab
  5. ----------
  6. Finds Matlab or Matlab Compiler Runtime (MCR) and provides Matlab tools,
  7. libraries and compilers to CMake.
  8. This package primary purpose is to find the libraries associated with Matlab
  9. or the MCR in order to be able to build Matlab extensions (mex files). It
  10. can also be used:
  11. * to run specific commands in Matlab in case Matlab is available
  12. * for declaring Matlab unit test
  13. * to retrieve various information from Matlab (mex extensions, versions and
  14. release queries, ...)
  15. .. versionadded:: 3.12
  16. Added Matlab Compiler Runtime (MCR) support.
  17. The module supports the following components:
  18. * ``ENG_LIBRARY`` and ``MAT_LIBRARY``: respectively the ``ENG`` and ``MAT``
  19. libraries of Matlab
  20. * ``MAIN_PROGRAM`` the Matlab binary program. Note that this component is not
  21. available on the MCR version, and will yield an error if the MCR is found
  22. instead of the regular Matlab installation.
  23. * ``MEX_COMPILER`` the MEX compiler.
  24. * ``MCC_COMPILER`` the MCC compiler, included with the Matlab Compiler add-on.
  25. * ``SIMULINK`` the Simulink environment.
  26. .. versionadded:: 3.7
  27. Added the ``MAT_LIBRARY`` component.
  28. .. versionadded:: 3.13
  29. Added the ``ENGINE_LIBRARY``, ``DATAARRAY_LIBRARY`` and ``MCC_COMPILER``
  30. components.
  31. .. versionchanged:: 3.14
  32. Removed the ``MX_LIBRARY``, ``ENGINE_LIBRARY`` and ``DATAARRAY_LIBRARY``
  33. components. These libraries are found unconditionally.
  34. .. note::
  35. The version given to the :command:`find_package` directive is the Matlab
  36. **version**, which should not be confused with the Matlab *release* name
  37. (eg. `R2014`).
  38. The :command:`matlab_get_version_from_release_name` and
  39. :command:`matlab_get_release_name_from_version` provide a mapping
  40. between the release name and the version.
  41. The variable :variable:`Matlab_ROOT_DIR` may be specified in order to give
  42. the path of the desired Matlab version. Otherwise, the behavior is platform
  43. specific:
  44. * Windows: The installed versions of Matlab/MCR are retrieved from the
  45. Windows registry
  46. * OS X: The installed versions of Matlab/MCR are given by the MATLAB
  47. default installation paths in ``/Application``. If no such application is
  48. found, it falls back to the one that might be accessible from the ``PATH``.
  49. * Unix: The desired Matlab should be accessible from the ``PATH``. This does
  50. not work for MCR installation and :variable:`Matlab_ROOT_DIR` should be
  51. specified on this platform.
  52. Additional information is provided when :variable:`MATLAB_FIND_DEBUG` is set.
  53. When a Matlab/MCR installation is found automatically and the ``MATLAB_VERSION``
  54. is not given, the version is queried from Matlab directly (on Windows this
  55. may pop up a Matlab window) or from the MCR installation.
  56. The mapping of the release names and the version of Matlab is performed by
  57. defining pairs (name, version). The variable
  58. :variable:`MATLAB_ADDITIONAL_VERSIONS` may be provided before the call to
  59. the :command:`find_package` in order to handle additional versions.
  60. A Matlab scripts can be added to the set of tests using the
  61. :command:`matlab_add_unit_test`. By default, the Matlab unit test framework
  62. will be used (>= 2013a) to run this script, but regular ``.m`` files
  63. returning an exit code can be used as well (0 indicating a success).
  64. Module Input Variables
  65. ^^^^^^^^^^^^^^^^^^^^^^
  66. Users or projects may set the following variables to configure the module
  67. behavior:
  68. :variable:`Matlab_ROOT <<PackageName>_ROOT>`
  69. .. versionadded:: 3.25
  70. Default value for :variable:`Matlab_ROOT_DIR`, the root of the Matlab
  71. installation.
  72. :variable:`Matlab_ROOT_DIR`
  73. The root of the Matlab installation.
  74. :variable:`MATLAB_FIND_DEBUG`
  75. outputs debug information
  76. :variable:`MATLAB_ADDITIONAL_VERSIONS`
  77. additional versions of Matlab for the automatic retrieval of the installed
  78. versions.
  79. Imported targets
  80. ^^^^^^^^^^^^^^^^
  81. .. versionadded:: 3.22
  82. This module defines the following :prop_tgt:`IMPORTED` targets:
  83. ``Matlab::mex``
  84. The ``mex`` library, always available.
  85. ``Matlab::mx``
  86. The mx library of Matlab (arrays), always available.
  87. ``Matlab::eng``
  88. Matlab engine library. Available only if the ``ENG_LIBRARY`` component
  89. is requested.
  90. ``Matlab::mat``
  91. Matlab matrix library. Available only if the ``MAT_LIBRARY`` component
  92. is requested.
  93. ``Matlab::MatlabEngine``
  94. Matlab C++ engine library, always available for R2018a and newer.
  95. ``Matlab::MatlabDataArray``
  96. Matlab C++ data array library, always available for R2018a and newer.
  97. Variables defined by the module
  98. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  99. Result variables
  100. """"""""""""""""
  101. ``Matlab_FOUND``
  102. ``TRUE`` if the Matlab installation is found, ``FALSE``
  103. otherwise. All variable below are defined if Matlab is found.
  104. ``Matlab_ROOT_DIR``
  105. the final root of the Matlab installation determined by the FindMatlab
  106. module.
  107. ``Matlab_MAIN_PROGRAM``
  108. the Matlab binary program. Available only if the component ``MAIN_PROGRAM``
  109. is given in the :command:`find_package` directive.
  110. ``Matlab_INCLUDE_DIRS``
  111. the path of the Matlab libraries headers
  112. ``Matlab_MEX_LIBRARY``
  113. library for mex, always available.
  114. ``Matlab_MX_LIBRARY``
  115. mx library of Matlab (arrays), always available.
  116. ``Matlab_ENG_LIBRARY``
  117. Matlab engine library. Available only if the component ``ENG_LIBRARY``
  118. is requested.
  119. ``Matlab_MAT_LIBRARY``
  120. Matlab matrix library. Available only if the component ``MAT_LIBRARY``
  121. is requested.
  122. ``Matlab_ENGINE_LIBRARY``
  123. .. versionadded:: 3.13
  124. Matlab C++ engine library, always available for R2018a and newer.
  125. ``Matlab_DATAARRAY_LIBRARY``
  126. .. versionadded:: 3.13
  127. Matlab C++ data array library, always available for R2018a and newer.
  128. ``Matlab_LIBRARIES``
  129. the whole set of libraries of Matlab
  130. ``Matlab_MEX_COMPILER``
  131. the mex compiler of Matlab. Currently not used.
  132. Available only if the component ``MEX_COMPILER`` is requested.
  133. ``Matlab_MCC_COMPILER``
  134. .. versionadded:: 3.13
  135. the mcc compiler of Matlab. Included with the Matlab Compiler add-on.
  136. Available only if the component ``MCC_COMPILER`` is requested.
  137. Cached variables
  138. """"""""""""""""
  139. ``Matlab_MEX_EXTENSION``
  140. the extension of the mex files for the current platform (given by Matlab).
  141. ``Matlab_ROOT_DIR``
  142. the location of the root of the Matlab installation found. If this value
  143. is changed by the user, the result variables are recomputed.
  144. Provided macros
  145. ^^^^^^^^^^^^^^^
  146. :command:`matlab_get_version_from_release_name`
  147. returns the version from the release name
  148. :command:`matlab_get_release_name_from_version`
  149. returns the release name from the Matlab version
  150. Provided functions
  151. ^^^^^^^^^^^^^^^^^^
  152. :command:`matlab_add_mex`
  153. adds a target compiling a MEX file.
  154. :command:`matlab_add_unit_test`
  155. adds a Matlab unit test file as a test to the project.
  156. :command:`matlab_extract_all_installed_versions_from_registry`
  157. parses the registry for all Matlab versions. Available on Windows only.
  158. The part of the registry parsed is dependent on the host processor
  159. :command:`matlab_get_all_valid_matlab_roots_from_registry`
  160. returns all the possible Matlab or MCR paths, according to a previously
  161. given list. Only the existing/accessible paths are kept. This is mainly
  162. useful for the searching all possible Matlab installation.
  163. :command:`matlab_get_mex_suffix`
  164. returns the suffix to be used for the mex files
  165. (platform/architecture dependent)
  166. :command:`matlab_get_version_from_matlab_run`
  167. returns the version of Matlab/MCR, given the full directory of the Matlab/MCR
  168. installation path.
  169. Known issues
  170. ^^^^^^^^^^^^
  171. **Symbol clash in a MEX target**
  172. By default, every symbols inside a MEX
  173. file defined with the command :command:`matlab_add_mex` have hidden
  174. visibility, except for the entry point. This is the default behavior of
  175. the MEX compiler, which lowers the risk of symbol collision between the
  176. libraries shipped with Matlab, and the libraries to which the MEX file is
  177. linking to. This is also the default on Windows platforms.
  178. However, this is not sufficient in certain case, where for instance your
  179. MEX file is linking against libraries that are already loaded by Matlab,
  180. even if those libraries have different SONAMES.
  181. A possible solution is to hide the symbols of the libraries to which the
  182. MEX target is linking to. This can be achieved in GNU GCC compilers with
  183. the linker option ``-Wl,--exclude-libs,ALL``.
  184. **Tests using GPU resources**
  185. in case your MEX file is using the GPU and
  186. in order to be able to run unit tests on this MEX file, the GPU resources
  187. should be properly released by Matlab. A possible solution is to make
  188. Matlab aware of the use of the GPU resources in the session, which can be
  189. performed by a command such as ``D = gpuDevice()`` at the beginning of
  190. the test script (or via a fixture).
  191. Reference
  192. ^^^^^^^^^
  193. .. variable:: Matlab_ROOT_DIR
  194. The root folder of the Matlab installation. If set before the call to
  195. :command:`find_package`, the module will look for the components in that
  196. path. If not set, then an automatic search of Matlab
  197. will be performed. If set, it should point to a valid version of Matlab.
  198. .. variable:: MATLAB_FIND_DEBUG
  199. If set, the lookup of Matlab and the intermediate configuration steps are
  200. outputted to the console.
  201. .. variable:: MATLAB_ADDITIONAL_VERSIONS
  202. If set, specifies additional versions of Matlab that may be looked for.
  203. The variable should be a list of strings, organized by pairs of release
  204. name and versions, such as follows::
  205. set(MATLAB_ADDITIONAL_VERSIONS
  206. "release_name1=corresponding_version1"
  207. "release_name2=corresponding_version2"
  208. ...
  209. )
  210. Example::
  211. set(MATLAB_ADDITIONAL_VERSIONS
  212. "R2013b=8.2"
  213. "R2013a=8.1"
  214. "R2012b=8.0")
  215. The order of entries in this list matters when several versions of
  216. Matlab are installed. The priority is set according to the ordering in
  217. this list.
  218. #]=======================================================================]
  219. cmake_policy(PUSH)
  220. cmake_policy(SET CMP0057 NEW) # if IN_LIST
  221. set(_FindMatlab_SELF_DIR "${CMAKE_CURRENT_LIST_DIR}")
  222. include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
  223. include(CheckCXXCompilerFlag)
  224. include(CheckCCompilerFlag)
  225. # The currently supported versions. Other version can be added by the user by
  226. # providing MATLAB_ADDITIONAL_VERSIONS
  227. if(NOT MATLAB_ADDITIONAL_VERSIONS)
  228. set(MATLAB_ADDITIONAL_VERSIONS)
  229. endif()
  230. set(MATLAB_VERSIONS_MAPPING
  231. "R2023a=9.14"
  232. "R2022b=9.13"
  233. "R2022a=9.12"
  234. "R2021b=9.11"
  235. "R2021a=9.10"
  236. "R2020b=9.9"
  237. "R2020a=9.8"
  238. "R2019b=9.7"
  239. "R2019a=9.6"
  240. "R2018b=9.5"
  241. "R2018a=9.4"
  242. "R2017b=9.3"
  243. "R2017a=9.2"
  244. "R2016b=9.1"
  245. "R2016a=9.0"
  246. "R2015b=8.6"
  247. "R2015a=8.5"
  248. "R2014b=8.4"
  249. "R2014a=8.3"
  250. "R2013b=8.2"
  251. "R2013a=8.1"
  252. "R2012b=8.0"
  253. "R2012a=7.14"
  254. "R2011b=7.13"
  255. "R2011a=7.12"
  256. "R2010b=7.11"
  257. ${MATLAB_ADDITIONAL_VERSIONS}
  258. )
  259. # temporary folder for all Matlab runs
  260. set(_matlab_temporary_folder ${CMAKE_BINARY_DIR}/Matlab)
  261. if(NOT EXISTS "${_matlab_temporary_folder}")
  262. file(MAKE_DIRECTORY "${_matlab_temporary_folder}")
  263. endif()
  264. #[=======================================================================[.rst:
  265. .. command:: matlab_get_version_from_release_name
  266. Returns the version of Matlab (17.58) from a release name (R2017k)
  267. #]=======================================================================]
  268. macro(matlab_get_version_from_release_name release_name version_name)
  269. string(REGEX MATCHALL "${release_name}=([0-9]+\\.?[0-9]*)" _matched ${MATLAB_VERSIONS_MAPPING})
  270. set(${version_name} "")
  271. if(NOT _matched STREQUAL "")
  272. set(${version_name} ${CMAKE_MATCH_1})
  273. else()
  274. message(WARNING "[MATLAB] The release name ${release_name} is not registered")
  275. endif()
  276. unset(_matched)
  277. endmacro()
  278. #[=======================================================================[.rst:
  279. .. command:: matlab_get_release_name_from_version
  280. Returns the release name (R2017k) from the version of Matlab (17.58)
  281. #]=======================================================================]
  282. macro(matlab_get_release_name_from_version version release_name)
  283. set(${release_name} "")
  284. foreach(_var IN LISTS MATLAB_VERSIONS_MAPPING)
  285. string(REGEX MATCHALL "(.+)=${version}" _matched ${_var})
  286. if(NOT _matched STREQUAL "")
  287. set(${release_name} ${CMAKE_MATCH_1})
  288. break()
  289. endif()
  290. endforeach(_var)
  291. unset(_var)
  292. unset(_matched)
  293. if(${release_name} STREQUAL "")
  294. message(WARNING "[MATLAB] The version ${version} is not registered")
  295. endif()
  296. endmacro()
  297. # extracts all the supported release names (R2017k...) of Matlab
  298. # internal use
  299. macro(matlab_get_supported_releases list_releases)
  300. set(${list_releases})
  301. foreach(_var IN LISTS MATLAB_VERSIONS_MAPPING)
  302. string(REGEX MATCHALL "(.+)=([0-9]+\\.?[0-9]*)" _matched ${_var})
  303. if(NOT _matched STREQUAL "")
  304. list(APPEND ${list_releases} ${CMAKE_MATCH_1})
  305. endif()
  306. unset(_matched)
  307. unset(CMAKE_MATCH_1)
  308. endforeach(_var)
  309. unset(_var)
  310. endmacro()
  311. # extracts all the supported versions of Matlab
  312. # internal use
  313. macro(matlab_get_supported_versions list_versions)
  314. set(${list_versions})
  315. foreach(_var IN LISTS MATLAB_VERSIONS_MAPPING)
  316. string(REGEX MATCHALL "(.+)=([0-9]+\\.?[0-9]*)" _matched ${_var})
  317. if(NOT _matched STREQUAL "")
  318. list(APPEND ${list_versions} ${CMAKE_MATCH_2})
  319. endif()
  320. unset(_matched)
  321. unset(CMAKE_MATCH_1)
  322. endforeach(_var)
  323. unset(_var)
  324. endmacro()
  325. #[=======================================================================[.rst:
  326. .. command:: matlab_extract_all_installed_versions_from_registry
  327. This function parses the registry and founds the Matlab versions that are
  328. installed. The found versions are returned in `matlab_versions`.
  329. Set `win64` to `TRUE` if the 64 bit version of Matlab should be looked for
  330. The returned list contains all versions under
  331. ``HKLM\\SOFTWARE\\Mathworks\\MATLAB`` and
  332. ``HKLM\\SOFTWARE\\Mathworks\\MATLAB Runtime`` or an empty list in case an
  333. error occurred (or nothing found).
  334. .. note::
  335. Only the versions are provided. No check is made over the existence of the
  336. installation referenced in the registry,
  337. #]=======================================================================]
  338. function(matlab_extract_all_installed_versions_from_registry win64 matlab_versions)
  339. if(NOT CMAKE_HOST_WIN32)
  340. message(FATAL_ERROR "[MATLAB] This macro can only be called by a windows host (call to reg.exe)")
  341. endif()
  342. if(${win64} AND CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "64")
  343. set(APPEND_REG "/reg:64")
  344. else()
  345. set(APPEND_REG "/reg:32")
  346. endif()
  347. set(matlabs_from_registry)
  348. foreach(_installation_type IN ITEMS "MATLAB" "MATLAB Runtime" "MATLAB Compiler Runtime")
  349. # /reg:64 should be added on 64 bits capable OSs in order to enable the
  350. # redirection of 64 bits applications
  351. execute_process(
  352. COMMAND reg query "HKEY_LOCAL_MACHINE\\SOFTWARE\\Mathworks\\${_installation_type}" /f * /k ${APPEND_REG}
  353. RESULT_VARIABLE resultMatlab
  354. OUTPUT_VARIABLE varMatlab
  355. ERROR_VARIABLE errMatlab
  356. INPUT_FILE NUL
  357. )
  358. if(resultMatlab EQUAL 0)
  359. string(
  360. REGEX MATCHALL "${_installation_type}\\\\([0-9]+(\\.[0-9]+)?)"
  361. matlab_versions_regex ${varMatlab})
  362. foreach(match IN LISTS matlab_versions_regex)
  363. string(
  364. REGEX MATCH "${_installation_type}\\\\(([0-9]+)(\\.([0-9]+))?)"
  365. current_match ${match})
  366. set(_matlab_current_version ${CMAKE_MATCH_1})
  367. set(current_matlab_version_major ${CMAKE_MATCH_2})
  368. set(current_matlab_version_minor ${CMAKE_MATCH_4})
  369. if(NOT current_matlab_version_minor)
  370. set(current_matlab_version_minor "0")
  371. endif()
  372. list(APPEND matlabs_from_registry ${_matlab_current_version})
  373. unset(_matlab_current_version)
  374. endforeach()
  375. endif()
  376. endforeach()
  377. if(matlabs_from_registry)
  378. list(REMOVE_DUPLICATES matlabs_from_registry)
  379. list(SORT matlabs_from_registry COMPARE NATURAL)
  380. list(REVERSE matlabs_from_registry)
  381. endif()
  382. set(${matlab_versions} ${matlabs_from_registry} PARENT_SCOPE)
  383. endfunction()
  384. # (internal)
  385. macro(extract_matlab_versions_from_registry_brute_force matlab_versions)
  386. # get the supported versions
  387. set(matlab_supported_versions)
  388. matlab_get_supported_versions(matlab_supported_versions)
  389. # this is a manual population of the versions we want to look for
  390. # this can be done as is, but preferably with the call to
  391. # matlab_get_supported_versions and variable
  392. # populating the versions we want to look for
  393. # set(matlab_supported_versions)
  394. # # Matlab 7
  395. # set(matlab_major 7)
  396. # foreach(current_matlab_minor RANGE 4 20)
  397. # list(APPEND matlab_supported_versions "${matlab_major}.${current_matlab_minor}")
  398. # endforeach(current_matlab_minor)
  399. # # Matlab 8
  400. # set(matlab_major 8)
  401. # foreach(current_matlab_minor RANGE 0 5)
  402. # list(APPEND matlab_supported_versions "${matlab_major}.${current_matlab_minor}")
  403. # endforeach(current_matlab_minor)
  404. # # taking into account the possible additional versions provided by the user
  405. # if(DEFINED MATLAB_ADDITIONAL_VERSIONS)
  406. # list(APPEND matlab_supported_versions MATLAB_ADDITIONAL_VERSIONS)
  407. # endif()
  408. # we order from more recent to older
  409. if(matlab_supported_versions)
  410. list(REMOVE_DUPLICATES matlab_supported_versions)
  411. list(SORT matlab_supported_versions COMPARE NATURAL)
  412. list(REVERSE matlab_supported_versions)
  413. endif()
  414. set(${matlab_versions} ${matlab_supported_versions})
  415. endmacro()
  416. #[=======================================================================[.rst:
  417. .. command:: matlab_get_all_valid_matlab_roots_from_registry
  418. Populates the Matlab root with valid versions of Matlab or
  419. Matlab Runtime (MCR).
  420. The returned matlab_roots is organized in triplets
  421. ``(type,version_number,matlab_root_path)``, where ``type``
  422. indicates either ``MATLAB`` or ``MCR``.
  423. ::
  424. matlab_get_all_valid_matlab_roots_from_registry(
  425. matlab_versions
  426. matlab_roots)
  427. ``matlab_versions``
  428. the versions of each of the Matlab or MCR installations
  429. ``matlab_roots``
  430. the location of each of the Matlab or MCR installations
  431. #]=======================================================================]
  432. function(matlab_get_all_valid_matlab_roots_from_registry matlab_versions matlab_roots)
  433. # The matlab_versions comes either from
  434. # extract_matlab_versions_from_registry_brute_force or
  435. # matlab_extract_all_installed_versions_from_registry.
  436. set(_matlab_roots_list )
  437. # check for Matlab installations
  438. foreach(_matlab_current_version ${matlab_versions})
  439. get_filename_component(
  440. current_MATLAB_ROOT
  441. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MathWorks\\MATLAB\\${_matlab_current_version};MATLABROOT]"
  442. ABSOLUTE)
  443. if(EXISTS "${current_MATLAB_ROOT}")
  444. list(APPEND _matlab_roots_list "MATLAB" ${_matlab_current_version} ${current_MATLAB_ROOT})
  445. endif()
  446. endforeach()
  447. # Check for MCR installations
  448. foreach(_matlab_current_version ${matlab_versions})
  449. get_filename_component(
  450. current_MATLAB_ROOT
  451. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MathWorks\\MATLAB Runtime\\${_matlab_current_version};MATLABROOT]"
  452. ABSOLUTE)
  453. # remove the dot
  454. string(REPLACE "." "" _matlab_current_version_without_dot "${_matlab_current_version}")
  455. if(EXISTS "${current_MATLAB_ROOT}")
  456. list(APPEND _matlab_roots_list "MCR" ${_matlab_current_version} "${current_MATLAB_ROOT}/v${_matlab_current_version_without_dot}")
  457. endif()
  458. endforeach()
  459. # Check for old MCR installations
  460. foreach(_matlab_current_version ${matlab_versions})
  461. get_filename_component(
  462. current_MATLAB_ROOT
  463. "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MathWorks\\MATLAB Compiler Runtime\\${_matlab_current_version};MATLABROOT]"
  464. ABSOLUTE)
  465. # remove the dot
  466. string(REPLACE "." "" _matlab_current_version_without_dot "${_matlab_current_version}")
  467. if(EXISTS "${current_MATLAB_ROOT}")
  468. list(APPEND _matlab_roots_list "MCR" ${_matlab_current_version} "${current_MATLAB_ROOT}/v${_matlab_current_version_without_dot}")
  469. endif()
  470. endforeach()
  471. set(${matlab_roots} ${_matlab_roots_list} PARENT_SCOPE)
  472. endfunction()
  473. #[=======================================================================[.rst:
  474. .. command:: matlab_get_mex_suffix
  475. Returns the extension of the mex files (the suffixes).
  476. This function should not be called before the appropriate Matlab root has
  477. been found.
  478. ::
  479. matlab_get_mex_suffix(
  480. matlab_root
  481. mex_suffix)
  482. ``matlab_root``
  483. the root of the Matlab/MCR installation
  484. ``mex_suffix``
  485. the variable name in which the suffix will be returned.
  486. #]=======================================================================]
  487. function(matlab_get_mex_suffix matlab_root mex_suffix)
  488. # find_program does not consider script suffix .bat for Matlab mexext.bat on Windows
  489. set(mexext_suffix "")
  490. if(WIN32)
  491. set(mexext_suffix ".bat")
  492. endif()
  493. find_program(
  494. Matlab_MEXEXTENSIONS_PROG
  495. NAMES mexext mexext${mexext_suffix}
  496. PATHS ${matlab_root}/bin
  497. DOC "Matlab MEX extension provider"
  498. NO_DEFAULT_PATH
  499. )
  500. if(MATLAB_FIND_DEBUG)
  501. message(STATUS "[MATLAB] Determining mex files extensions from '${matlab_root}/bin' with program '${Matlab_MEXEXTENSIONS_PROG}'")
  502. endif()
  503. # the program has been found?
  504. if(NOT Matlab_MEXEXTENSIONS_PROG)
  505. if(MATLAB_FIND_DEBUG)
  506. message(WARNING "[MATLAB] Cannot found mexext program. Matlab root is ${matlab_root}")
  507. endif()
  508. unset(Matlab_MEXEXTENSIONS_PROG CACHE)
  509. return()
  510. endif()
  511. set(_matlab_mex_extension)
  512. set(devnull)
  513. if(UNIX)
  514. set(devnull INPUT_FILE /dev/null)
  515. elseif(WIN32)
  516. set(devnull INPUT_FILE NUL)
  517. endif()
  518. if(WIN32)
  519. # this environment variable is used to determine the arch on Windows
  520. if(CMAKE_SIZEOF_VOID_P EQUAL 8)
  521. set(ENV{MATLAB_ARCH} "win64")
  522. else()
  523. set(ENV{MATLAB_ARCH} "win32")
  524. endif()
  525. endif()
  526. # this is the preferred way. If this does not work properly (eg. MCR on Windows), then we use our own knowledge
  527. execute_process(
  528. COMMAND ${Matlab_MEXEXTENSIONS_PROG}
  529. OUTPUT_VARIABLE _matlab_mex_extension
  530. ERROR_VARIABLE _matlab_mex_extension_error
  531. OUTPUT_STRIP_TRAILING_WHITESPACE
  532. ${devnull})
  533. unset(ENV{MATLAB_ARCH})
  534. if(_matlab_mex_extension_error)
  535. if(WIN32)
  536. # this is only for intel architecture
  537. if(CMAKE_SIZEOF_VOID_P EQUAL 8)
  538. set(_matlab_mex_extension "mexw64")
  539. else()
  540. set(_matlab_mex_extension "mexw32")
  541. endif()
  542. endif()
  543. endif()
  544. string(STRIP "${_matlab_mex_extension}" _matlab_mex_extension)
  545. if(MATLAB_FIND_DEBUG)
  546. message(STATUS "[MATLAB] '${Matlab_MEXEXTENSIONS_PROG}' : determined extension '${_matlab_mex_extension}' and error string is '${_matlab_mex_extension_error}'")
  547. endif()
  548. set(${mex_suffix} ${_matlab_mex_extension} PARENT_SCOPE)
  549. endfunction()
  550. #[=======================================================================[.rst:
  551. .. command:: matlab_get_version_from_matlab_run
  552. This function runs Matlab program specified on arguments and extracts its
  553. version. If the path provided for the Matlab installation points to an MCR
  554. installation, the version is extracted from the installed files.
  555. ::
  556. matlab_get_version_from_matlab_run(
  557. matlab_binary_path
  558. matlab_list_versions)
  559. ``matlab_binary_path``
  560. the location of the `matlab` binary executable
  561. ``matlab_list_versions``
  562. the version extracted from Matlab
  563. #]=======================================================================]
  564. function(matlab_get_version_from_matlab_run matlab_binary_program matlab_list_versions)
  565. set(${matlab_list_versions} "" PARENT_SCOPE)
  566. if(MATLAB_FIND_DEBUG)
  567. message(STATUS "[MATLAB] Determining the version of Matlab from ${matlab_binary_program}")
  568. endif()
  569. if(EXISTS "${_matlab_temporary_folder}/matlabVersionLog.cmaketmp")
  570. if(MATLAB_FIND_DEBUG)
  571. message(STATUS "[MATLAB] Removing previous ${_matlab_temporary_folder}/matlabVersionLog.cmaketmp file")
  572. endif()
  573. file(REMOVE "${_matlab_temporary_folder}/matlabVersionLog.cmaketmp")
  574. endif()
  575. # the log file is needed since on windows the command executes in a new
  576. # window and it is not possible to get back the answer of Matlab
  577. # the -wait command is needed on windows, otherwise the call returns
  578. # immediately after the program launches itself.
  579. if(WIN32)
  580. set(_matlab_additional_commands "-wait")
  581. endif()
  582. set(devnull)
  583. if(UNIX)
  584. set(devnull INPUT_FILE /dev/null)
  585. elseif(WIN32)
  586. set(devnull INPUT_FILE NUL)
  587. endif()
  588. # we first try to run a simple program using the -r option, and then we use the
  589. # -batch option that is supported and recommended since R2019a
  590. set(_matlab_get_version_failed_with_r_option FALSE)
  591. # timeout set to 120 seconds, in case it does not start
  592. # note as said before OUTPUT_VARIABLE cannot be used in a platform
  593. # independent manner however, not setting it would flush the output of Matlab
  594. # in the current console (unix variant)
  595. execute_process(
  596. COMMAND "${matlab_binary_program}" -nosplash -nojvm ${_matlab_additional_commands} -logfile "matlabVersionLog.cmaketmp" -nodesktop -nodisplay -r "version, exit"
  597. OUTPUT_VARIABLE _matlab_version_from_cmd_dummy
  598. RESULT_VARIABLE _matlab_result_version_call
  599. ERROR_VARIABLE _matlab_result_version_call_error
  600. TIMEOUT 120
  601. WORKING_DIRECTORY "${_matlab_temporary_folder}"
  602. ${devnull}
  603. )
  604. if(_matlab_result_version_call MATCHES "timeout")
  605. if(MATLAB_FIND_DEBUG)
  606. message(WARNING "[MATLAB] Unable to determine the version of Matlab."
  607. " Matlab call with -r option timed out after 120 seconds.")
  608. endif()
  609. set(_matlab_get_version_failed_with_r_option TRUE)
  610. endif()
  611. if(NOT ${_matlab_get_version_failed_with_r_option} AND ${_matlab_result_version_call})
  612. if(MATLAB_FIND_DEBUG)
  613. message(WARNING "[MATLAB] Unable to determine the version of Matlab. Matlab call with -r option returned with error ${_matlab_result_version_call}.")
  614. endif()
  615. set(_matlab_get_version_failed_with_r_option TRUE)
  616. elseif(NOT ${_matlab_get_version_failed_with_r_option} AND NOT EXISTS "${_matlab_temporary_folder}/matlabVersionLog.cmaketmp")
  617. if(MATLAB_FIND_DEBUG)
  618. message(WARNING "[MATLAB] Unable to determine the version of Matlab. The log file does not exist.")
  619. endif()
  620. set(_matlab_get_version_failed_with_r_option TRUE)
  621. endif()
  622. if(_matlab_get_version_failed_with_r_option)
  623. execute_process(
  624. COMMAND "${matlab_binary_program}" -nosplash -nojvm ${_matlab_additional_commands} -logfile "matlabVersionLog.cmaketmp" -nodesktop -nodisplay -batch "version, exit"
  625. OUTPUT_VARIABLE _matlab_version_from_cmd_dummy_batch
  626. RESULT_VARIABLE _matlab_result_version_call_batch
  627. ERROR_VARIABLE _matlab_result_version_call_error_batch
  628. TIMEOUT 120
  629. WORKING_DIRECTORY "${_matlab_temporary_folder}"
  630. ${devnull}
  631. )
  632. if(_matlab_result_version_call_batch MATCHES "timeout")
  633. if(MATLAB_FIND_DEBUG)
  634. message(WARNING "[MATLAB] Unable to determine the version of Matlab."
  635. " Matlab call with -batch option timed out after 120 seconds.")
  636. endif()
  637. return()
  638. endif()
  639. if(${_matlab_result_version_call_batch})
  640. if(MATLAB_FIND_DEBUG)
  641. message(WARNING "[MATLAB] Command executed \"${matlab_binary_program}\" -nosplash -nojvm ${_matlab_additional_commands} -logfile \"matlabVersionLog.cmaketmp\" -nodesktop -nodisplay -batch \"version, exit\"")
  642. message(WARNING "_matlab_version_from_cmd_dummy_batch (OUTPUT_VARIABLE): ${_matlab_version_from_cmd_dummy_batch}")
  643. message(WARNING "_matlab_result_version_call_batch (RESULT_VARIABLE): ${_matlab_result_version_call_batch}")
  644. message(WARNING "_matlab_result_version_call_error_batch (ERROR_VARIABLE): ${_matlab_result_version_call_error_batch}")
  645. message(WARNING "[MATLAB] Unable to determine the version of Matlab. Matlab call with -batch option returned with error ${_matlab_result_version_call_batch}.")
  646. endif()
  647. return()
  648. elseif(NOT ${_matlab_get_version_failed_with_r_option} AND NOT EXISTS "${_matlab_temporary_folder}/matlabVersionLog.cmaketmp")
  649. if(MATLAB_FIND_DEBUG)
  650. message(WARNING "[MATLAB] Unable to determine the version of Matlab. The log file does not exist.")
  651. endif()
  652. return()
  653. endif()
  654. endif()
  655. if(NOT EXISTS "${_matlab_temporary_folder}/matlabVersionLog.cmaketmp")
  656. # last resort check as some HPC with "module load matlab" not enacted fail to catch in earlier checks
  657. # and error CMake configure even if find_package(Matlab) is not REQUIRED
  658. if(MATLAB_FIND_DEBUG)
  659. message(WARNING "[MATLAB] Unable to determine the version of Matlab. The version log file does not exist.")
  660. endif()
  661. return()
  662. endif()
  663. # if successful, read back the log
  664. file(READ "${_matlab_temporary_folder}/matlabVersionLog.cmaketmp" _matlab_version_from_cmd)
  665. file(REMOVE "${_matlab_temporary_folder}/matlabVersionLog.cmaketmp")
  666. set(index -1)
  667. string(FIND "${_matlab_version_from_cmd}" "ans" index)
  668. if(index EQUAL -1)
  669. if(MATLAB_FIND_DEBUG)
  670. message(WARNING "[MATLAB] Cannot find the version of Matlab returned by the run.")
  671. endif()
  672. else()
  673. set(matlab_list_of_all_versions_tmp)
  674. string(SUBSTRING "${_matlab_version_from_cmd}" ${index} -1 substring_ans)
  675. string(
  676. REGEX MATCHALL "ans[\r\n\t ]*=[\r\n\t ]*'?([0-9]+(\\.[0-9]+)?)"
  677. matlab_versions_regex
  678. ${substring_ans})
  679. foreach(match IN LISTS matlab_versions_regex)
  680. string(
  681. REGEX MATCH "ans[\r\n\t ]*=[\r\n\t ]*'?(([0-9]+)(\\.([0-9]+))?)"
  682. current_match ${match})
  683. list(APPEND matlab_list_of_all_versions_tmp ${CMAKE_MATCH_1})
  684. endforeach()
  685. if(matlab_list_of_all_versions_tmp)
  686. list(REMOVE_DUPLICATES matlab_list_of_all_versions_tmp)
  687. endif()
  688. set(${matlab_list_versions} ${matlab_list_of_all_versions_tmp} PARENT_SCOPE)
  689. endif()
  690. endfunction()
  691. #[=======================================================================[.rst:
  692. .. command:: matlab_add_unit_test
  693. Adds a Matlab unit test to the test set of cmake/ctest.
  694. This command requires the component ``MAIN_PROGRAM`` and hence is not
  695. available for an MCR installation.
  696. The unit test uses the Matlab unittest framework (default, available
  697. starting Matlab 2013b+) except if the option ``NO_UNITTEST_FRAMEWORK``
  698. is given.
  699. The function expects one Matlab test script file to be given.
  700. In the case ``NO_UNITTEST_FRAMEWORK`` is given, the unittest script file
  701. should contain the script to be run, plus an exit command with the exit
  702. value. This exit value will be passed to the ctest framework (0 success,
  703. non 0 failure). Additional arguments accepted by :command:`add_test` can be
  704. passed through ``TEST_ARGS`` (eg. ``CONFIGURATION <config> ...``).
  705. ::
  706. matlab_add_unit_test(
  707. NAME <name>
  708. UNITTEST_FILE matlab_file_containing_unittest.m
  709. [CUSTOM_TEST_COMMAND matlab_command_to_run_as_test]
  710. [UNITTEST_PRECOMMAND matlab_command_to_run]
  711. [TIMEOUT timeout]
  712. [ADDITIONAL_PATH path1 [path2 ...]]
  713. [MATLAB_ADDITIONAL_STARTUP_OPTIONS option1 [option2 ...]]
  714. [TEST_ARGS arg1 [arg2 ...]]
  715. [NO_UNITTEST_FRAMEWORK]
  716. )
  717. The function arguments are:
  718. ``NAME``
  719. name of the unittest in ctest.
  720. ``UNITTEST_FILE``
  721. the matlab unittest file. Its path will be automatically
  722. added to the Matlab path.
  723. ``CUSTOM_TEST_COMMAND``
  724. Matlab script command to run as the test.
  725. If this is not set, then the following is run:
  726. ``runtests('matlab_file_name'), exit(max([ans(1,:).Failed]))``
  727. where ``matlab_file_name`` is the ``UNITTEST_FILE`` without the extension.
  728. ``UNITTEST_PRECOMMAND``
  729. Matlab script command to be ran before the file
  730. containing the test (eg. GPU device initialization based on CMake
  731. variables).
  732. ``TIMEOUT``
  733. the test timeout in seconds. Defaults to 180 seconds as the
  734. Matlab unit test may hang.
  735. ``ADDITIONAL_PATH``
  736. a list of paths to add to the Matlab path prior to
  737. running the unit test.
  738. ``MATLAB_ADDITIONAL_STARTUP_OPTIONS``
  739. a list of additional option in order
  740. to run Matlab from the command line.
  741. ``-nosplash -nodesktop -nodisplay`` are always added.
  742. ``TEST_ARGS``
  743. Additional options provided to the add_test command. These
  744. options are added to the default options (eg. "CONFIGURATIONS Release")
  745. ``NO_UNITTEST_FRAMEWORK``
  746. when set, indicates that the test should not
  747. use the unittest framework of Matlab (available for versions >= R2013a).
  748. ``WORKING_DIRECTORY``
  749. This will be the working directory for the test. If specified it will
  750. also be the output directory used for the log file of the test run.
  751. If not specified the temporary directory ``${CMAKE_BINARY_DIR}/Matlab`` will
  752. be used as the working directory and the log location.
  753. #]=======================================================================]
  754. function(matlab_add_unit_test)
  755. if(NOT Matlab_MAIN_PROGRAM)
  756. message(FATAL_ERROR "[MATLAB] This functionality needs the MAIN_PROGRAM component (not default)")
  757. endif()
  758. set(options NO_UNITTEST_FRAMEWORK)
  759. set(oneValueArgs NAME UNITTEST_FILE TIMEOUT WORKING_DIRECTORY
  760. UNITTEST_PRECOMMAND CUSTOM_TEST_COMMAND)
  761. set(multiValueArgs ADDITIONAL_PATH MATLAB_ADDITIONAL_STARTUP_OPTIONS TEST_ARGS)
  762. set(prefix _matlab_unittest_prefix)
  763. cmake_parse_arguments(PARSE_ARGV 0 ${prefix} "${options}" "${oneValueArgs}" "${multiValueArgs}" )
  764. if(NOT ${prefix}_NAME)
  765. message(FATAL_ERROR "[MATLAB] The Matlab test name cannot be empty")
  766. endif()
  767. # The option to run a batch program with MATLAB changes depending on the MATLAB version
  768. # For MATLAB before R2019a (9.6), the only supported option is -r, afterwords the suggested option
  769. # is -batch as -r is deprecated
  770. set(maut_BATCH_OPTION "-r")
  771. if(NOT (Matlab_VERSION_STRING STREQUAL ""))
  772. if(Matlab_VERSION_STRING VERSION_GREATER_EQUAL "9.6")
  773. set(maut_BATCH_OPTION "-batch")
  774. endif()
  775. endif()
  776. add_test(NAME ${${prefix}_NAME}
  777. COMMAND ${CMAKE_COMMAND}
  778. "-Dtest_name=${${prefix}_NAME}"
  779. "-Dadditional_paths=${${prefix}_ADDITIONAL_PATH}"
  780. "-Dtest_timeout=${${prefix}_TIMEOUT}"
  781. "-Doutput_directory=${_matlab_temporary_folder}"
  782. "-Dworking_directory=${${prefix}_WORKING_DIRECTORY}"
  783. "-DMatlab_PROGRAM=${Matlab_MAIN_PROGRAM}"
  784. "-Dno_unittest_framework=${${prefix}_NO_UNITTEST_FRAMEWORK}"
  785. "-DMatlab_ADDITIONAL_STARTUP_OPTIONS=${${prefix}_MATLAB_ADDITIONAL_STARTUP_OPTIONS}"
  786. "-Dunittest_file_to_run=${${prefix}_UNITTEST_FILE}"
  787. "-Dcustom_Matlab_test_command=${${prefix}_CUSTOM_TEST_COMMAND}"
  788. "-Dcmd_to_run_before_test=${${prefix}_UNITTEST_PRECOMMAND}"
  789. "-Dmaut_BATCH_OPTION=${maut_BATCH_OPTION}"
  790. -P ${_FindMatlab_SELF_DIR}/MatlabTestsRedirect.cmake
  791. ${${prefix}_TEST_ARGS}
  792. ${${prefix}_UNPARSED_ARGUMENTS}
  793. )
  794. endfunction()
  795. #[=======================================================================[.rst:
  796. .. command:: matlab_add_mex
  797. Adds a Matlab MEX target.
  798. This commands compiles the given sources with the current tool-chain in
  799. order to produce a MEX file. The final name of the produced output may be
  800. specified, as well as additional link libraries, and a documentation entry
  801. for the MEX file. Remaining arguments of the call are passed to the
  802. :command:`add_library` or :command:`add_executable` command.
  803. ::
  804. matlab_add_mex(
  805. NAME <name>
  806. [EXECUTABLE | MODULE | SHARED]
  807. SRC src1 [src2 ...]
  808. [OUTPUT_NAME output_name]
  809. [DOCUMENTATION file.txt]
  810. [LINK_TO target1 target2 ...]
  811. [R2017b | R2018a]
  812. [EXCLUDE_FROM_ALL]
  813. [NO_IMPLICIT_LINK_TO_MATLAB_LIBRARIES]
  814. [...]
  815. )
  816. ``NAME``
  817. name of the target.
  818. ``SRC``
  819. list of source files.
  820. ``LINK_TO``
  821. a list of additional link dependencies. The target links to ``libmex``
  822. and ``libmx`` by default, unless the
  823. ``NO_IMPLICIT_LINK_TO_MATLAB_LIBRARIES`` option is passed.
  824. ``OUTPUT_NAME``
  825. if given, overrides the default name. The default name is
  826. the name of the target without any prefix and
  827. with ``Matlab_MEX_EXTENSION`` suffix.
  828. ``DOCUMENTATION``
  829. if given, the file ``file.txt`` will be considered as
  830. being the documentation file for the MEX file. This file is copied into
  831. the same folder without any processing, with the same name as the final
  832. mex file, and with extension `.m`. In that case, typing ``help <name>``
  833. in Matlab prints the documentation contained in this file.
  834. ``R2017b`` or ``R2018a``
  835. .. versionadded:: 3.14
  836. May be given to specify the version of the C API
  837. to use: ``R2017b`` specifies the traditional (separate complex) C API,
  838. and corresponds to the ``-R2017b`` flag for the `mex` command. ``R2018a``
  839. specifies the new interleaved complex C API, and corresponds to the
  840. ``-R2018a`` flag for the `mex` command. Ignored if MATLAB version prior
  841. to R2018a. Defaults to ``R2017b``.
  842. ``MODULE`` or ``SHARED``
  843. .. versionadded:: 3.7
  844. May be given to specify the type of library to be
  845. created.
  846. ``EXECUTABLE``
  847. .. versionadded:: 3.7
  848. May be given to create an executable instead of
  849. a library. If no type is given explicitly, the type is ``SHARED``.
  850. ``EXCLUDE_FROM_ALL``
  851. This option has the same meaning as for :prop_tgt:`EXCLUDE_FROM_ALL` and
  852. is forwarded to :command:`add_library` or :command:`add_executable`
  853. commands.
  854. ``NO_IMPLICIT_LINK_TO_MATLAB_LIBRARIES``
  855. .. versionadded:: 3.24
  856. This option permits to disable the automatic linking of MATLAB
  857. libraries, so that only the libraries that are actually required can be
  858. linked via the ``LINK_TO`` option.
  859. The documentation file is not processed and should be in the following
  860. format:
  861. ::
  862. % This is the documentation
  863. function ret = mex_target_output_name(input1)
  864. #]=======================================================================]
  865. function(matlab_add_mex)
  866. if(NOT WIN32)
  867. # we do not need all this on Windows
  868. # pthread options
  869. if(CMAKE_CXX_COMPILER_LOADED)
  870. check_cxx_compiler_flag(-pthread HAS_MINUS_PTHREAD)
  871. elseif(CMAKE_C_COMPILER_LOADED)
  872. check_c_compiler_flag(-pthread HAS_MINUS_PTHREAD)
  873. endif()
  874. # we should use try_compile instead, the link flags are discarded from
  875. # this compiler_flag function.
  876. #check_cxx_compiler_flag(-Wl,--exclude-libs,ALL HAS_SYMBOL_HIDING_CAPABILITY)
  877. endif()
  878. set(options EXECUTABLE MODULE SHARED R2017b R2018a EXCLUDE_FROM_ALL NO_IMPLICIT_LINK_TO_MATLAB_LIBRARIES)
  879. set(oneValueArgs NAME DOCUMENTATION OUTPUT_NAME)
  880. set(multiValueArgs LINK_TO SRC)
  881. set(prefix _matlab_addmex_prefix)
  882. cmake_parse_arguments(${prefix} "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} )
  883. if(NOT ${prefix}_NAME)
  884. message(FATAL_ERROR "[MATLAB] The MEX target name cannot be empty")
  885. endif()
  886. if(NOT ${prefix}_OUTPUT_NAME)
  887. set(${prefix}_OUTPUT_NAME ${${prefix}_NAME})
  888. endif()
  889. if(NOT Matlab_VERSION_STRING VERSION_LESS "9.1") # For 9.1 (R2016b) and newer, add version source file
  890. # Add the correct version file depending on which languages are enabled in the project
  891. if(CMAKE_C_COMPILER_LOADED)
  892. # If C is enabled, use the .c file as it will work fine also with C++
  893. set(MEX_VERSION_FILE "${Matlab_ROOT_DIR}/extern/version/c_mexapi_version.c")
  894. elseif(CMAKE_CXX_COMPILER_LOADED)
  895. # If C is not enabled, check if CXX is enabled and use the .cpp file
  896. # to avoid that the .c file is silently ignored
  897. set(MEX_VERSION_FILE "${Matlab_ROOT_DIR}/extern/version/cpp_mexapi_version.cpp")
  898. else()
  899. # If neither C or CXX is enabled, warn because we cannot add the source.
  900. # TODO: add support for fortran mex files
  901. message(WARNING "[MATLAB] matlab_add_mex requires that at least C or CXX are enabled languages")
  902. endif()
  903. endif()
  904. # For 9.4 (R2018a) and newer, add API macro.
  905. # Add it for unknown versions too, just in case.
  906. if(NOT Matlab_VERSION_STRING VERSION_LESS "9.4"
  907. OR Matlab_VERSION_STRING STREQUAL "unknown")
  908. if(${${prefix}_R2018a})
  909. set(MEX_API_MACRO "MATLAB_DEFAULT_RELEASE=R2018a")
  910. else()
  911. set(MEX_API_MACRO "MATLAB_DEFAULT_RELEASE=R2017b")
  912. endif()
  913. endif()
  914. set(_option_EXCLUDE_FROM_ALL)
  915. if(${prefix}_EXCLUDE_FROM_ALL)
  916. set(_option_EXCLUDE_FROM_ALL "EXCLUDE_FROM_ALL")
  917. endif()
  918. if(${prefix}_EXECUTABLE)
  919. add_executable(${${prefix}_NAME}
  920. ${_option_EXCLUDE_FROM_ALL}
  921. ${${prefix}_SRC}
  922. ${MEX_VERSION_FILE}
  923. ${${prefix}_DOCUMENTATION}
  924. ${${prefix}_UNPARSED_ARGUMENTS})
  925. else()
  926. if(${prefix}_MODULE)
  927. set(type MODULE)
  928. else()
  929. set(type SHARED)
  930. endif()
  931. add_library(${${prefix}_NAME}
  932. ${type}
  933. ${_option_EXCLUDE_FROM_ALL}
  934. ${${prefix}_SRC}
  935. ${MEX_VERSION_FILE}
  936. ${${prefix}_DOCUMENTATION}
  937. ${${prefix}_UNPARSED_ARGUMENTS})
  938. endif()
  939. target_include_directories(${${prefix}_NAME} SYSTEM PRIVATE ${Matlab_INCLUDE_DIRS})
  940. if(NOT ${prefix}_NO_IMPLICIT_LINK_TO_MATLAB_LIBRARIES)
  941. if(Matlab_HAS_CPP_API)
  942. if(Matlab_ENGINE_LIBRARY)
  943. target_link_libraries(${${prefix}_NAME} ${Matlab_ENGINE_LIBRARY})
  944. endif()
  945. if(Matlab_DATAARRAY_LIBRARY)
  946. target_link_libraries(${${prefix}_NAME} ${Matlab_DATAARRAY_LIBRARY})
  947. endif()
  948. endif()
  949. target_link_libraries(${${prefix}_NAME} ${Matlab_MEX_LIBRARY} ${Matlab_MX_LIBRARY})
  950. endif()
  951. target_link_libraries(${${prefix}_NAME} ${${prefix}_LINK_TO})
  952. set_target_properties(${${prefix}_NAME}
  953. PROPERTIES
  954. PREFIX ""
  955. OUTPUT_NAME ${${prefix}_OUTPUT_NAME}
  956. SUFFIX ".${Matlab_MEX_EXTENSION}")
  957. target_compile_definitions(${${prefix}_NAME} PRIVATE ${MEX_API_MACRO} MATLAB_MEX_FILE)
  958. # documentation
  959. if(NOT ${${prefix}_DOCUMENTATION} STREQUAL "")
  960. get_target_property(output_name ${${prefix}_NAME} OUTPUT_NAME)
  961. add_custom_command(
  962. TARGET ${${prefix}_NAME}
  963. PRE_BUILD
  964. COMMAND ${CMAKE_COMMAND} -E copy_if_different ${${prefix}_DOCUMENTATION} $<TARGET_FILE_DIR:${${prefix}_NAME}>/${output_name}.m
  965. COMMENT "[MATLAB] Copy ${${prefix}_NAME} documentation file into the output folder"
  966. )
  967. endif() # documentation
  968. # entry point in the mex file + taking care of visibility and symbol clashes.
  969. if(WIN32)
  970. if (MSVC)
  971. set(_link_flags "${_link_flags} /EXPORT:mexFunction")
  972. if(NOT Matlab_VERSION_STRING VERSION_LESS "9.1") # For 9.1 (R2016b) and newer, export version
  973. set(_link_flags "${_link_flags} /EXPORT:mexfilerequiredapiversion")
  974. endif()
  975. set_property(TARGET ${${prefix}_NAME} APPEND PROPERTY LINK_FLAGS ${_link_flags})
  976. endif() # No other compiler currently supported on Windows.
  977. set_target_properties(${${prefix}_NAME}
  978. PROPERTIES
  979. DEFINE_SYMBOL "DLL_EXPORT_SYM=__declspec(dllexport)")
  980. else()
  981. if(Matlab_VERSION_STRING VERSION_LESS "9.1") # For versions prior to 9.1 (R2016b)
  982. set(_ver_map_files ${Matlab_EXTERN_LIBRARY_DIR}/mexFunction.map)
  983. else() # For 9.1 (R2016b) and newer
  984. set(_ver_map_files ${Matlab_EXTERN_LIBRARY_DIR}/c_exportsmexfileversion.map)
  985. endif()
  986. if(NOT Matlab_VERSION_STRING VERSION_LESS "9.5") # For 9.5 (R2018b) (and newer?)
  987. target_compile_options(${${prefix}_NAME} PRIVATE "-fvisibility=default")
  988. # This one is weird, it might be a bug in <mex.h> for R2018b. When compiling with
  989. # -fvisibility=hidden, the symbol `mexFunction` cannot be exported. Reading the
  990. # source code for <mex.h>, it seems that the preprocessor macro `MW_NEEDS_VERSION_H`
  991. # needs to be defined for `__attribute__((visibility("default")))` to be added
  992. # in front of the declaration of `mexFunction`. In previous versions of MATLAB this
  993. # was not the case, there `DLL_EXPORT_SYM` needed to be defined.
  994. # Adding `-fvisibility=hidden` to the `mex` command causes the build to fail.
  995. # TODO: Check that this is still necessary in R2019a when it comes out.
  996. endif()
  997. if(APPLE)
  998. if(Matlab_HAS_CPP_API)
  999. list(APPEND _ver_map_files ${Matlab_EXTERN_LIBRARY_DIR}/cppMexFunction.map) # This one doesn't exist on Linux
  1000. set(_link_flags "${_link_flags} -Wl,-U,_mexCreateMexFunction -Wl,-U,_mexDestroyMexFunction -Wl,-U,_mexFunctionAdapter")
  1001. # On MacOS, the MEX command adds the above, without it the link breaks
  1002. # because we indiscriminately use "cppMexFunction.map" even for C API MEX-files.
  1003. endif()
  1004. set(_export_flag_name -exported_symbols_list)
  1005. else() # Linux
  1006. if(HAS_MINUS_PTHREAD)
  1007. # Apparently, compiling with -pthread generated the proper link flags
  1008. # and some defines at compilation
  1009. target_compile_options(${${prefix}_NAME} PRIVATE "-pthread")
  1010. endif()
  1011. set(_link_flags "${_link_flags} -Wl,--as-needed")
  1012. set(_export_flag_name --version-script)
  1013. endif()
  1014. foreach(_file ${_ver_map_files})
  1015. set(_link_flags "${_link_flags} -Wl,${_export_flag_name},${_file}")
  1016. endforeach()
  1017. # The `mex` command doesn't add this define. It is specified here in order
  1018. # to export the symbol in case the client code decides to hide its symbols
  1019. set_target_properties(${${prefix}_NAME}
  1020. PROPERTIES
  1021. DEFINE_SYMBOL "DLL_EXPORT_SYM=__attribute__((visibility(\"default\")))"
  1022. LINK_FLAGS "${_link_flags}"
  1023. )
  1024. endif()
  1025. endfunction()
  1026. # (internal)
  1027. # Used to get the version of matlab, using caching. This basically transforms the
  1028. # output of the root list, with possible unknown version, to a version
  1029. # This can possibly run Matlab for extracting the version.
  1030. function(_Matlab_get_version_from_root matlab_root matlab_or_mcr matlab_known_version matlab_final_version)
  1031. # if the version is not trivial, we query matlab (if not MCR) for that
  1032. # we keep track of the location of matlab that induced this version
  1033. #if(NOT DEFINED Matlab_PROG_VERSION_STRING_AUTO_DETECT)
  1034. # set(Matlab_PROG_VERSION_STRING_AUTO_DETECT "" CACHE INTERNAL "internal matlab location for the discovered version")
  1035. #endif()
  1036. if(NOT matlab_known_version STREQUAL "NOTFOUND")
  1037. # the version is known, we just return it
  1038. set(${matlab_final_version} ${matlab_known_version} PARENT_SCOPE)
  1039. set(Matlab_VERSION_STRING_INTERNAL ${matlab_known_version} CACHE INTERNAL "Matlab version (automatically determined)" FORCE)
  1040. return()
  1041. endif()
  1042. if(matlab_or_mcr STREQUAL "UNKNOWN")
  1043. if(MATLAB_FIND_DEBUG)
  1044. message(WARNING "[MATLAB] Determining Matlab or MCR")
  1045. endif()
  1046. if(EXISTS "${matlab_root}/appdata/version.xml")
  1047. # we inspect the application version.xml file that contains the product information
  1048. file(STRINGS "${matlab_root}/appdata/version.xml" productinfo_string NEWLINE_CONSUME)
  1049. string(REGEX MATCH "<installedProductData.*displayedString=\"([a-zA-Z ]+)\".*/>"
  1050. product_reg_match
  1051. ${productinfo_string}
  1052. )
  1053. # default fallback to Matlab
  1054. set(matlab_or_mcr "MATLAB")
  1055. if(NOT CMAKE_MATCH_1 STREQUAL "")
  1056. string(TOLOWER "${CMAKE_MATCH_1}" product_reg_match)
  1057. if(product_reg_match STREQUAL "matlab runtime")
  1058. set(matlab_or_mcr "MCR")
  1059. endif()
  1060. endif()
  1061. endif()
  1062. if(MATLAB_FIND_DEBUG)
  1063. message(WARNING "[MATLAB] '${matlab_root}' contains the '${matlab_or_mcr}'")
  1064. endif()
  1065. endif()
  1066. # UNKNOWN is the default behavior in case we
  1067. # - have an erroneous matlab_root
  1068. # - have an initial 'UNKNOWN'
  1069. if(matlab_or_mcr STREQUAL "MATLAB" OR matlab_or_mcr STREQUAL "UNKNOWN")
  1070. # MATLAB versions
  1071. set(_matlab_current_program ${Matlab_MAIN_PROGRAM})
  1072. # do we already have a matlab program?
  1073. if(NOT _matlab_current_program)
  1074. set(_find_matlab_options)
  1075. if(matlab_root AND EXISTS ${matlab_root})
  1076. set(_find_matlab_options PATHS ${matlab_root} ${matlab_root}/bin NO_DEFAULT_PATH)
  1077. endif()
  1078. find_program(
  1079. _matlab_current_program
  1080. matlab
  1081. ${_find_matlab_options}
  1082. DOC "Matlab main program"
  1083. )
  1084. endif()
  1085. if(NOT _matlab_current_program OR NOT EXISTS ${_matlab_current_program})
  1086. # if not found, clear the dependent variables
  1087. if(MATLAB_FIND_DEBUG)
  1088. message(WARNING "[MATLAB] Cannot find the main matlab program under ${matlab_root}")
  1089. endif()
  1090. set(Matlab_PROG_VERSION_STRING_AUTO_DETECT "" CACHE INTERNAL "internal matlab location for the discovered version" FORCE)
  1091. set(Matlab_VERSION_STRING_INTERNAL "" CACHE INTERNAL "internal matlab location for the discovered version" FORCE)
  1092. unset(_matlab_current_program)
  1093. unset(_matlab_current_program CACHE)
  1094. return()
  1095. endif()
  1096. # full real path for path comparison
  1097. get_filename_component(_matlab_main_real_path_tmp "${_matlab_current_program}" REALPATH)
  1098. unset(_matlab_current_program)
  1099. unset(_matlab_current_program CACHE)
  1100. # is it the same as the previous one?
  1101. if(_matlab_main_real_path_tmp STREQUAL Matlab_PROG_VERSION_STRING_AUTO_DETECT)
  1102. set(${matlab_final_version} ${Matlab_VERSION_STRING_INTERNAL} PARENT_SCOPE)
  1103. return()
  1104. endif()
  1105. # update the location of the program
  1106. set(Matlab_PROG_VERSION_STRING_AUTO_DETECT
  1107. ${_matlab_main_real_path_tmp}
  1108. CACHE INTERNAL "internal matlab location for the discovered version" FORCE)
  1109. set(matlab_list_of_all_versions)
  1110. matlab_get_version_from_matlab_run("${Matlab_PROG_VERSION_STRING_AUTO_DETECT}" matlab_list_of_all_versions)
  1111. list(LENGTH matlab_list_of_all_versions list_of_all_versions_length)
  1112. if(list_of_all_versions_length GREATER 0)
  1113. list(GET matlab_list_of_all_versions 0 _matlab_version_tmp)
  1114. else()
  1115. set(_matlab_version_tmp "unknown")
  1116. endif()
  1117. # set the version into the cache
  1118. set(Matlab_VERSION_STRING_INTERNAL ${_matlab_version_tmp} CACHE INTERNAL "Matlab version (automatically determined)" FORCE)
  1119. # warning, just in case several versions found (should not happen)
  1120. if((list_of_all_versions_length GREATER 1) AND MATLAB_FIND_DEBUG)
  1121. message(WARNING "[MATLAB] Found several versions, taking the first one (versions found ${matlab_list_of_all_versions})")
  1122. endif()
  1123. # return the updated value
  1124. set(${matlab_final_version} ${Matlab_VERSION_STRING_INTERNAL} PARENT_SCOPE)
  1125. elseif(EXISTS "${matlab_root}/VersionInfo.xml")
  1126. # MCR
  1127. # we cannot run anything in order to extract the version. We assume that the file
  1128. # VersionInfo.xml exists under the MatlabRoot, we look for it and extract the version from there
  1129. set(_matlab_version_tmp "unknown")
  1130. file(STRINGS "${matlab_root}/VersionInfo.xml" versioninfo_string NEWLINE_CONSUME)
  1131. if(versioninfo_string)
  1132. # parses "<version>9.2.0.538062</version>"
  1133. string(REGEX MATCH "<version>(.*)</version>"
  1134. version_reg_match
  1135. ${versioninfo_string}
  1136. )
  1137. if(CMAKE_MATCH_1 MATCHES "(([0-9]+)\\.([0-9]+))[\\.0-9]*")
  1138. set(_matlab_version_tmp "${CMAKE_MATCH_1}")
  1139. endif()
  1140. endif()
  1141. set(${matlab_final_version} "${_matlab_version_tmp}" PARENT_SCOPE)
  1142. set(Matlab_VERSION_STRING_INTERNAL
  1143. "${_matlab_version_tmp}"
  1144. CACHE INTERNAL "Matlab (MCR) version (automatically determined)"
  1145. FORCE)
  1146. endif() # Matlab or MCR
  1147. endfunction()
  1148. # Utility function for finding Matlab or MCR on Win32
  1149. function(_Matlab_find_instances_win32 matlab_roots)
  1150. # On WIN32, we look for Matlab installation in the registry
  1151. # if unsuccessful, we look for all known revision and filter the existing
  1152. # ones.
  1153. # testing if we are able to extract the needed information from the registry
  1154. set(_matlab_versions_from_registry)
  1155. if(CMAKE_SIZEOF_VOID_P EQUAL 8)
  1156. set(_matlab_win64 ON)
  1157. else()
  1158. set(_matlab_win64 OFF)
  1159. endif()
  1160. matlab_extract_all_installed_versions_from_registry(_matlab_win64 _matlab_versions_from_registry)
  1161. # the returned list is empty, doing the search on all known versions
  1162. if(NOT _matlab_versions_from_registry)
  1163. if(MATLAB_FIND_DEBUG)
  1164. message(STATUS "[MATLAB] Search for Matlab from the registry unsuccessful, testing all supported versions")
  1165. endif()
  1166. extract_matlab_versions_from_registry_brute_force(_matlab_versions_from_registry)
  1167. endif()
  1168. # filtering the results with the registry keys
  1169. matlab_get_all_valid_matlab_roots_from_registry("${_matlab_versions_from_registry}" _matlab_possible_roots)
  1170. set(${matlab_roots} ${_matlab_possible_roots} PARENT_SCOPE)
  1171. endfunction()
  1172. # Utility function for finding Matlab or MCR on OSX
  1173. function(_Matlab_find_instances_osx matlab_roots)
  1174. set(_matlab_possible_roots)
  1175. # on mac, we look for the /Application paths
  1176. # this corresponds to the behavior on Windows. On Linux, we do not have
  1177. # any other guess.
  1178. matlab_get_supported_releases(_matlab_releases)
  1179. if(MATLAB_FIND_DEBUG)
  1180. message(STATUS "[MATLAB] Matlab supported versions ${_matlab_releases}. If more version should be supported "
  1181. "the variable MATLAB_ADDITIONAL_VERSIONS can be set according to the documentation")
  1182. endif()
  1183. foreach(_matlab_current_release IN LISTS _matlab_releases)
  1184. matlab_get_version_from_release_name("${_matlab_current_release}" _matlab_current_version)
  1185. string(REPLACE "." "" _matlab_current_version_without_dot "${_matlab_current_version}")
  1186. set(_matlab_base_path "/Applications/MATLAB_${_matlab_current_release}.app")
  1187. # Check Matlab, has precedence over MCR
  1188. if(EXISTS ${_matlab_base_path})
  1189. if(MATLAB_FIND_DEBUG)
  1190. message(STATUS "[MATLAB] Found version ${_matlab_current_release} (${_matlab_current_version}) in ${_matlab_base_path}")
  1191. endif()
  1192. list(APPEND _matlab_possible_roots "MATLAB" ${_matlab_current_version} ${_matlab_base_path})
  1193. endif()
  1194. # Checks MCR
  1195. set(_mcr_path "/Applications/MATLAB/MATLAB_Runtime/v${_matlab_current_version_without_dot}")
  1196. if(EXISTS "${_mcr_path}")
  1197. if(MATLAB_FIND_DEBUG)
  1198. message(STATUS "[MATLAB] Found MCR version ${_matlab_current_release} (${_matlab_current_version}) in ${_mcr_path}")
  1199. endif()
  1200. list(APPEND _matlab_possible_roots "MCR" ${_matlab_current_version} ${_mcr_path})
  1201. endif()
  1202. endforeach()
  1203. set(${matlab_roots} ${_matlab_possible_roots} PARENT_SCOPE)
  1204. endfunction()
  1205. # Utility function for finding Matlab or MCR from the PATH
  1206. function(_Matlab_find_instances_from_path matlab_roots)
  1207. set(_matlab_possible_roots)
  1208. # At this point, we have no other choice than trying to find it from PATH.
  1209. # If set by the user, this won't change.
  1210. find_program(
  1211. _matlab_main_tmp
  1212. NAMES matlab)
  1213. if(_matlab_main_tmp)
  1214. # we then populate the list of roots, with empty version
  1215. if(MATLAB_FIND_DEBUG)
  1216. message(STATUS "[MATLAB] matlab found from PATH: ${_matlab_main_tmp}")
  1217. endif()
  1218. # resolve symlinks
  1219. get_filename_component(_matlab_current_location "${_matlab_main_tmp}" REALPATH)
  1220. # get the directory (the command below has to be run twice)
  1221. # this will be the matlab root
  1222. get_filename_component(_matlab_current_location "${_matlab_current_location}" DIRECTORY)
  1223. get_filename_component(_matlab_current_location "${_matlab_current_location}" DIRECTORY) # Matlab should be in bin
  1224. # We found the Matlab program
  1225. list(APPEND _matlab_possible_roots "MATLAB" "NOTFOUND" ${_matlab_current_location})
  1226. # we remove this from the CACHE
  1227. unset(_matlab_main_tmp CACHE)
  1228. else()
  1229. find_program(
  1230. _matlab_mex_tmp
  1231. NAMES mex)
  1232. if(_matlab_mex_tmp)
  1233. # we then populate the list of roots, with empty version
  1234. if(MATLAB_FIND_DEBUG)
  1235. message(STATUS "[MATLAB] mex compiler found from PATH: ${_matlab_mex_tmp}")
  1236. endif()
  1237. # resolve symlinks
  1238. get_filename_component(_mex_current_location "${_matlab_mex_tmp}" REALPATH)
  1239. # get the directory (the command below has to be run twice)
  1240. # this will be the matlab root
  1241. get_filename_component(_mex_current_location "${_mex_current_location}" DIRECTORY)
  1242. get_filename_component(_mex_current_location "${_mex_current_location}" DIRECTORY) # Matlab Runtime mex compiler should be in bin
  1243. # We found the Matlab program
  1244. list(APPEND _matlab_possible_roots "MCR" "NOTFOUND" ${_mex_current_location})
  1245. unset(_matlab_mex_tmp CACHE)
  1246. else()
  1247. if(MATLAB_FIND_DEBUG)
  1248. message(STATUS "[MATLAB] mex compiler not found")
  1249. endif()
  1250. endif()
  1251. endif()
  1252. set(${matlab_roots} ${_matlab_possible_roots} PARENT_SCOPE)
  1253. endfunction()
  1254. # ###################################
  1255. # Exploring the possible Matlab_ROOTS
  1256. # this variable will get all Matlab installations found in the current system.
  1257. set(_matlab_possible_roots)
  1258. if(NOT DEFINED Matlab_ROOT AND DEFINED ENV{Matlab_ROOT})
  1259. set(Matlab_ROOT $ENV{Matlab_ROOT})
  1260. endif()
  1261. if(DEFINED Matlab_ROOT)
  1262. set(Matlab_ROOT_DIR ${Matlab_ROOT})
  1263. endif()
  1264. if(Matlab_ROOT_DIR)
  1265. # if the user specifies a possible root, we keep this one
  1266. if(NOT EXISTS "${Matlab_ROOT_DIR}")
  1267. # if Matlab_ROOT_DIR specified but erroneous
  1268. if(MATLAB_FIND_DEBUG)
  1269. message(WARNING "[MATLAB] the specified path for Matlab_ROOT_DIR does not exist (${Matlab_ROOT_DIR})")
  1270. endif()
  1271. else()
  1272. # NOTFOUND indicates the code below to search for the version automatically
  1273. if("${Matlab_VERSION_STRING_INTERNAL}" STREQUAL "")
  1274. list(APPEND _matlab_possible_roots "UNKNOWN" "NOTFOUND" ${Matlab_ROOT_DIR}) # empty version, empty MCR/Matlab indication
  1275. else()
  1276. list(APPEND _matlab_possible_roots "UNKNOWN" ${Matlab_VERSION_STRING_INTERNAL} ${Matlab_ROOT_DIR}) # cached version
  1277. endif()
  1278. endif()
  1279. else()
  1280. # if the user does not specify the possible installation root, we look for
  1281. # one installation using the appropriate heuristics.
  1282. # There is apparently no standard way on Linux.
  1283. if(CMAKE_HOST_WIN32)
  1284. _Matlab_find_instances_win32(_matlab_possible_roots_win32)
  1285. list(APPEND _matlab_possible_roots ${_matlab_possible_roots_win32})
  1286. elseif(APPLE)
  1287. _Matlab_find_instances_osx(_matlab_possible_roots_osx)
  1288. list(APPEND _matlab_possible_roots ${_matlab_possible_roots_osx})
  1289. endif()
  1290. endif()
  1291. list(LENGTH _matlab_possible_roots _numbers_of_matlab_roots)
  1292. if(_numbers_of_matlab_roots EQUAL 0)
  1293. # if we have not found anything, we fall back on the PATH
  1294. _Matlab_find_instances_from_path(_matlab_possible_roots)
  1295. endif()
  1296. if(MATLAB_FIND_DEBUG)
  1297. message(STATUS "[MATLAB] Matlab root folders are ${_matlab_possible_roots}")
  1298. endif()
  1299. # take the first possible Matlab root
  1300. list(LENGTH _matlab_possible_roots _numbers_of_matlab_roots)
  1301. set(Matlab_VERSION_STRING "NOTFOUND")
  1302. set(Matlab_Or_MCR "UNKNOWN")
  1303. if(_numbers_of_matlab_roots GREATER 0)
  1304. if(Matlab_FIND_VERSION_EXACT)
  1305. list(FIND _matlab_possible_roots ${Matlab_FIND_VERSION} _list_index)
  1306. if(_list_index LESS 0)
  1307. set(_list_index 1)
  1308. endif()
  1309. math(EXPR _matlab_or_mcr_index "${_list_index} - 1")
  1310. math(EXPR _matlab_root_dir_index "${_list_index} + 1")
  1311. list(GET _matlab_possible_roots ${_matlab_or_mcr_index} Matlab_Or_MCR)
  1312. list(GET _matlab_possible_roots ${_list_index} Matlab_VERSION_STRING)
  1313. list(GET _matlab_possible_roots ${_matlab_root_dir_index} Matlab_ROOT_DIR)
  1314. elseif(DEFINED Matlab_FIND_VERSION)
  1315. set(_list_index -1)
  1316. foreach(_matlab_root_index RANGE 1 ${_numbers_of_matlab_roots} 3)
  1317. list(GET _matlab_possible_roots ${_matlab_root_index} _matlab_root_version)
  1318. if(_matlab_root_version VERSION_GREATER_EQUAL Matlab_FIND_VERSION)
  1319. set(_list_index ${_matlab_root_index})
  1320. break()
  1321. endif()
  1322. endforeach()
  1323. if(_list_index LESS 0)
  1324. set(_list_index 1)
  1325. endif()
  1326. math(EXPR _matlab_or_mcr_index "${_list_index} - 1")
  1327. math(EXPR _matlab_root_dir_index "${_list_index} + 1")
  1328. list(GET _matlab_possible_roots ${_matlab_or_mcr_index} Matlab_Or_MCR)
  1329. list(GET _matlab_possible_roots ${_list_index} Matlab_VERSION_STRING)
  1330. list(GET _matlab_possible_roots ${_matlab_root_dir_index} Matlab_ROOT_DIR)
  1331. # adding a warning in case of ambiguity
  1332. if(_numbers_of_matlab_roots GREATER 3 AND MATLAB_FIND_DEBUG)
  1333. message(WARNING "[MATLAB] Found several distributions of Matlab. Setting the current version to ${Matlab_VERSION_STRING} (located ${Matlab_ROOT_DIR})."
  1334. " If this is not the desired behavior, use the EXACT keyword or provide the -DMatlab_ROOT_DIR=... on the command line")
  1335. endif()
  1336. else()
  1337. list(GET _matlab_possible_roots 0 Matlab_Or_MCR)
  1338. list(GET _matlab_possible_roots 1 Matlab_VERSION_STRING)
  1339. list(GET _matlab_possible_roots 2 Matlab_ROOT_DIR)
  1340. # adding a warning in case of ambiguity
  1341. if(_numbers_of_matlab_roots GREATER 3 AND MATLAB_FIND_DEBUG)
  1342. message(WARNING "[MATLAB] Found several distributions of Matlab. Setting the current version to ${Matlab_VERSION_STRING} (located ${Matlab_ROOT_DIR})."
  1343. " If this is not the desired behavior, use the EXACT keyword or provide the -DMatlab_ROOT_DIR=... on the command line")
  1344. endif()
  1345. endif()
  1346. endif()
  1347. # check if the root changed wrt. the previous defined one, if so
  1348. # clear all the cached variables for being able to reconfigure properly
  1349. if(DEFINED Matlab_ROOT_DIR_LAST_CACHED)
  1350. if(NOT Matlab_ROOT_DIR_LAST_CACHED STREQUAL Matlab_ROOT_DIR)
  1351. set(_Matlab_cached_vars
  1352. Matlab_VERSION_STRING
  1353. Matlab_INCLUDE_DIRS
  1354. Matlab_MEX_LIBRARY
  1355. Matlab_MEX_COMPILER
  1356. Matlab_MCC_COMPILER
  1357. Matlab_MAIN_PROGRAM
  1358. Matlab_MX_LIBRARY
  1359. Matlab_ENG_LIBRARY
  1360. Matlab_MAT_LIBRARY
  1361. Matlab_ENGINE_LIBRARY
  1362. Matlab_DATAARRAY_LIBRARY
  1363. Matlab_MEX_EXTENSION
  1364. Matlab_SIMULINK_INCLUDE_DIR
  1365. # internal
  1366. Matlab_MEXEXTENSIONS_PROG
  1367. Matlab_ROOT_DIR_LAST_CACHED
  1368. #Matlab_PROG_VERSION_STRING_AUTO_DETECT
  1369. #Matlab_VERSION_STRING_INTERNAL
  1370. )
  1371. foreach(_var IN LISTS _Matlab_cached_vars)
  1372. if(DEFINED ${_var})
  1373. unset(${_var} CACHE)
  1374. endif()
  1375. endforeach()
  1376. endif()
  1377. endif()
  1378. set(Matlab_ROOT_DIR_LAST_CACHED ${Matlab_ROOT_DIR} CACHE INTERNAL "last Matlab root dir location")
  1379. set(Matlab_ROOT_DIR ${Matlab_ROOT_DIR} CACHE PATH "Matlab installation root path" FORCE)
  1380. # Fix the version, in case this one is NOTFOUND
  1381. _Matlab_get_version_from_root(
  1382. "${Matlab_ROOT_DIR}"
  1383. "${Matlab_Or_MCR}"
  1384. ${Matlab_VERSION_STRING}
  1385. Matlab_VERSION_STRING
  1386. )
  1387. if(MATLAB_FIND_DEBUG)
  1388. message(STATUS "[MATLAB] Current version is ${Matlab_VERSION_STRING} located ${Matlab_ROOT_DIR}")
  1389. endif()
  1390. # MATLAB 9.4 (R2018a) and newer have a new C++ API
  1391. # This API pulls additional required libraries.
  1392. if(NOT ${Matlab_VERSION_STRING} VERSION_LESS "9.4")
  1393. set(Matlab_HAS_CPP_API 1)
  1394. endif()
  1395. if(Matlab_ROOT_DIR)
  1396. file(TO_CMAKE_PATH ${Matlab_ROOT_DIR} Matlab_ROOT_DIR)
  1397. endif()
  1398. if(CMAKE_SIZEOF_VOID_P EQUAL 4)
  1399. set(_matlab_64Build FALSE)
  1400. else()
  1401. set(_matlab_64Build TRUE)
  1402. endif()
  1403. if(NOT DEFINED Matlab_MEX_EXTENSION)
  1404. set(_matlab_mex_extension "")
  1405. matlab_get_mex_suffix("${Matlab_ROOT_DIR}" _matlab_mex_extension)
  1406. # This variable goes to the cache.
  1407. set(Matlab_MEX_EXTENSION ${_matlab_mex_extension} CACHE STRING "Extensions for the mex targets (automatically given by Matlab)")
  1408. unset(_matlab_mex_extension)
  1409. endif()
  1410. if(APPLE)
  1411. set(_matlab_bin_prefix "mac") # i should be for intel
  1412. set(_matlab_bin_suffix_32bits "i")
  1413. if(CMAKE_SYSTEM_PROCESSOR STREQUAL "arm64" AND Matlab_MEX_EXTENSION MATCHES "a64$")
  1414. # native Apple Silicon Matlab
  1415. set(_matlab_bin_suffix_64bits "a64")
  1416. else()
  1417. # Intel Mac OR Apple Silicon using Rosetta for Matlab
  1418. set(_matlab_bin_suffix_64bits "i64")
  1419. endif()
  1420. elseif(UNIX)
  1421. set(_matlab_bin_prefix "gln")
  1422. set(_matlab_bin_suffix_32bits "x86")
  1423. set(_matlab_bin_suffix_64bits "xa64")
  1424. else()
  1425. set(_matlab_bin_prefix "win")
  1426. set(_matlab_bin_suffix_32bits "32")
  1427. set(_matlab_bin_suffix_64bits "64")
  1428. endif()
  1429. set(MATLAB_INCLUDE_DIR_TO_LOOK ${Matlab_ROOT_DIR}/extern/include)
  1430. if(_matlab_64Build)
  1431. set(_matlab_current_suffix ${_matlab_bin_suffix_64bits})
  1432. else()
  1433. set(_matlab_current_suffix ${_matlab_bin_suffix_32bits})
  1434. endif()
  1435. set(Matlab_BINARIES_DIR
  1436. ${Matlab_ROOT_DIR}/bin/${_matlab_bin_prefix}${_matlab_current_suffix})
  1437. set(Matlab_EXTERN_LIBRARY_DIR
  1438. ${Matlab_ROOT_DIR}/extern/lib/${_matlab_bin_prefix}${_matlab_current_suffix})
  1439. set(Matlab_EXTERN_BINARIES_DIR
  1440. ${Matlab_ROOT_DIR}/extern/bin/${_matlab_bin_prefix}${_matlab_current_suffix})
  1441. if(WIN32)
  1442. if(MINGW)
  1443. set(_matlab_lib_dir_for_search ${Matlab_EXTERN_LIBRARY_DIR}/mingw64)
  1444. else()
  1445. set(_matlab_lib_dir_for_search ${Matlab_EXTERN_LIBRARY_DIR}/microsoft)
  1446. endif()
  1447. set(_matlab_lib_prefix_for_search "lib")
  1448. else()
  1449. set(_matlab_lib_dir_for_search ${Matlab_BINARIES_DIR} ${Matlab_EXTERN_BINARIES_DIR})
  1450. set(_matlab_lib_prefix_for_search "lib")
  1451. endif()
  1452. unset(_matlab_64Build)
  1453. if(MATLAB_FIND_DEBUG)
  1454. message(STATUS "[MATLAB] [DEBUG]_matlab_lib_prefix_for_search = ${_matlab_lib_prefix_for_search} | _matlab_lib_dir_for_search = ${_matlab_lib_dir_for_search}")
  1455. endif()
  1456. # internal
  1457. # This small stub around find_library is to prevent any pollution of CMAKE_FIND_LIBRARY_PREFIXES in the global scope.
  1458. # This is the function to be used below instead of the find_library directives.
  1459. function(_Matlab_find_library _matlab_library_prefix)
  1460. set(CMAKE_FIND_LIBRARY_PREFIXES ${CMAKE_FIND_LIBRARY_PREFIXES} ${_matlab_library_prefix})
  1461. find_library(${ARGN})
  1462. endfunction()
  1463. set(_matlab_required_variables)
  1464. # Order is as follow:
  1465. # - unconditionally required libraries/headers first
  1466. # - then library components
  1467. # - then program components
  1468. # the MEX library/header are required
  1469. find_path(
  1470. Matlab_INCLUDE_DIRS
  1471. mex.h
  1472. PATHS ${MATLAB_INCLUDE_DIR_TO_LOOK}
  1473. NO_DEFAULT_PATH
  1474. )
  1475. list(APPEND _matlab_required_variables Matlab_INCLUDE_DIRS)
  1476. if(Matlab_Or_MCR STREQUAL "MATLAB" OR Matlab_Or_MCR STREQUAL "UNKNOWN")
  1477. _Matlab_find_library(
  1478. ${_matlab_lib_prefix_for_search}
  1479. Matlab_MEX_LIBRARY
  1480. mex
  1481. PATHS ${_matlab_lib_dir_for_search}
  1482. NO_DEFAULT_PATH
  1483. )
  1484. list(APPEND _matlab_required_variables Matlab_MEX_LIBRARY)
  1485. # the MEX extension is required
  1486. list(APPEND _matlab_required_variables Matlab_MEX_EXTENSION)
  1487. # the matlab root is required
  1488. list(APPEND _matlab_required_variables Matlab_ROOT_DIR)
  1489. # The MX library is required
  1490. _Matlab_find_library(
  1491. ${_matlab_lib_prefix_for_search}
  1492. Matlab_MX_LIBRARY
  1493. mx
  1494. PATHS ${_matlab_lib_dir_for_search}
  1495. NO_DEFAULT_PATH
  1496. )
  1497. list(APPEND _matlab_required_variables Matlab_MX_LIBRARY)
  1498. if(Matlab_MX_LIBRARY)
  1499. set(Matlab_MX_LIBRARY_FOUND TRUE)
  1500. endif()
  1501. endif()
  1502. if(Matlab_HAS_CPP_API)
  1503. # The MatlabEngine library is required for R2018a+
  1504. _Matlab_find_library(
  1505. ${_matlab_lib_prefix_for_search}
  1506. Matlab_ENGINE_LIBRARY
  1507. MatlabEngine
  1508. PATHS ${_matlab_lib_dir_for_search}
  1509. DOC "MatlabEngine Library"
  1510. NO_DEFAULT_PATH
  1511. )
  1512. if(Matlab_ENGINE_LIBRARY)
  1513. set(Matlab_ENGINE_LIBRARY_FOUND TRUE)
  1514. endif()
  1515. # The MatlabDataArray library is required for R2018a+
  1516. _Matlab_find_library(
  1517. ${_matlab_lib_prefix_for_search}
  1518. Matlab_DATAARRAY_LIBRARY
  1519. MatlabDataArray
  1520. PATHS ${_matlab_lib_dir_for_search}
  1521. DOC "MatlabDataArray Library"
  1522. NO_DEFAULT_PATH
  1523. )
  1524. if(Matlab_DATAARRAY_LIBRARY)
  1525. set(Matlab_DATAARRAY_LIBRARY_FOUND TRUE)
  1526. endif()
  1527. endif()
  1528. # Component ENG library
  1529. if("ENG_LIBRARY" IN_LIST Matlab_FIND_COMPONENTS)
  1530. _Matlab_find_library(
  1531. ${_matlab_lib_prefix_for_search}
  1532. Matlab_ENG_LIBRARY
  1533. eng
  1534. PATHS ${_matlab_lib_dir_for_search}
  1535. NO_DEFAULT_PATH
  1536. )
  1537. if(Matlab_ENG_LIBRARY)
  1538. set(Matlab_ENG_LIBRARY_FOUND TRUE)
  1539. endif()
  1540. endif()
  1541. # Component MAT library
  1542. if("MAT_LIBRARY" IN_LIST Matlab_FIND_COMPONENTS)
  1543. _Matlab_find_library(
  1544. ${_matlab_lib_prefix_for_search}
  1545. Matlab_MAT_LIBRARY
  1546. mat
  1547. PATHS ${_matlab_lib_dir_for_search}
  1548. NO_DEFAULT_PATH
  1549. )
  1550. if(Matlab_MAT_LIBRARY)
  1551. set(Matlab_MAT_LIBRARY_FOUND TRUE)
  1552. endif()
  1553. endif()
  1554. # Component Simulink
  1555. if("SIMULINK" IN_LIST Matlab_FIND_COMPONENTS)
  1556. find_path(
  1557. Matlab_SIMULINK_INCLUDE_DIR
  1558. simstruc.h
  1559. PATHS "${Matlab_ROOT_DIR}/simulink/include"
  1560. NO_DEFAULT_PATH
  1561. )
  1562. if(Matlab_SIMULINK_INCLUDE_DIR)
  1563. set(Matlab_SIMULINK_FOUND TRUE)
  1564. list(APPEND Matlab_INCLUDE_DIRS "${Matlab_SIMULINK_INCLUDE_DIR}")
  1565. endif()
  1566. endif()
  1567. # component Matlab program
  1568. if("MAIN_PROGRAM" IN_LIST Matlab_FIND_COMPONENTS)
  1569. find_program(
  1570. Matlab_MAIN_PROGRAM
  1571. matlab
  1572. PATHS ${Matlab_ROOT_DIR} ${Matlab_ROOT_DIR}/bin
  1573. DOC "Matlab main program"
  1574. NO_DEFAULT_PATH
  1575. )
  1576. if(Matlab_MAIN_PROGRAM)
  1577. set(Matlab_MAIN_PROGRAM_FOUND TRUE)
  1578. endif()
  1579. endif()
  1580. # component Mex Compiler
  1581. if("MEX_COMPILER" IN_LIST Matlab_FIND_COMPONENTS)
  1582. find_program(
  1583. Matlab_MEX_COMPILER
  1584. "mex"
  1585. PATHS ${Matlab_BINARIES_DIR}
  1586. DOC "Matlab MEX compiler"
  1587. NO_DEFAULT_PATH
  1588. )
  1589. if(Matlab_MEX_COMPILER)
  1590. set(Matlab_MEX_COMPILER_FOUND TRUE)
  1591. endif()
  1592. endif()
  1593. # component MCC Compiler
  1594. if("MCC_COMPILER" IN_LIST Matlab_FIND_COMPONENTS)
  1595. find_program(
  1596. Matlab_MCC_COMPILER
  1597. "mcc"
  1598. PATHS ${Matlab_BINARIES_DIR}
  1599. DOC "Matlab MCC compiler"
  1600. NO_DEFAULT_PATH
  1601. )
  1602. if(Matlab_MCC_COMPILER)
  1603. set(Matlab_MCC_COMPILER_FOUND TRUE)
  1604. endif()
  1605. endif()
  1606. set(Matlab_LIBRARIES
  1607. ${Matlab_MEX_LIBRARY} ${Matlab_MX_LIBRARY}
  1608. ${Matlab_ENG_LIBRARY} ${Matlab_MAT_LIBRARY})
  1609. if(Matlab_ENGINE_LIBRARY)
  1610. list(APPEND Matlab_LIBRARIES ${Matlab_ENGINE_LIBRARY})
  1611. endif()
  1612. if(Matlab_DATAARRAY_LIBRARY)
  1613. list(APPEND Matlab_LIBRARIES ${Matlab_DATAARRAY_LIBRARY})
  1614. endif()
  1615. # internal
  1616. # This small stub permits to add imported targets for the found MATLAB libraries
  1617. function(_Matlab_add_imported_target _matlab_library_variable_name _matlab_library_target_name)
  1618. if(Matlab_${_matlab_library_variable_name}_LIBRARY)
  1619. if(NOT TARGET Matlab::${_matlab_library_target_name})
  1620. add_library(Matlab::${_matlab_library_target_name} UNKNOWN IMPORTED)
  1621. set_target_properties(Matlab::${_matlab_library_target_name} PROPERTIES
  1622. INTERFACE_INCLUDE_DIRECTORIES "${Matlab_INCLUDE_DIRS}"
  1623. IMPORTED_LOCATION "${Matlab_${_matlab_library_variable_name}_LIBRARY}")
  1624. if(_matlab_library_target_name STREQUAL "mex" OR
  1625. _matlab_library_target_name STREQUAL "eng" OR
  1626. _matlab_library_target_name STREQUAL "mat")
  1627. set_target_properties(Matlab::${_matlab_library_target_name} PROPERTIES
  1628. INTERFACE_LINK_LIBRARIES Matlab::mx)
  1629. endif()
  1630. endif()
  1631. endif()
  1632. endfunction()
  1633. _Matlab_add_imported_target(MX mx)
  1634. _Matlab_add_imported_target(MEX mex)
  1635. _Matlab_add_imported_target(ENG eng)
  1636. _Matlab_add_imported_target(MAT mat)
  1637. _Matlab_add_imported_target(ENGINE MatlabEngine)
  1638. _Matlab_add_imported_target(DATAARRAY MatlabDataArray)
  1639. find_package_handle_standard_args(
  1640. Matlab
  1641. FOUND_VAR Matlab_FOUND
  1642. REQUIRED_VARS ${_matlab_required_variables}
  1643. VERSION_VAR Matlab_VERSION_STRING
  1644. HANDLE_COMPONENTS)
  1645. unset(_matlab_required_variables)
  1646. unset(_matlab_bin_prefix)
  1647. unset(_matlab_bin_suffix_32bits)
  1648. unset(_matlab_bin_suffix_64bits)
  1649. unset(_matlab_current_suffix)
  1650. unset(_matlab_lib_dir_for_search)
  1651. unset(_matlab_lib_prefix_for_search)
  1652. if(Matlab_INCLUDE_DIRS AND Matlab_LIBRARIES)
  1653. mark_as_advanced(
  1654. Matlab_MEX_LIBRARY
  1655. Matlab_MX_LIBRARY
  1656. Matlab_ENG_LIBRARY
  1657. Matlab_ENGINE_LIBRARY
  1658. Matlab_DATAARRAY_LIBRARY
  1659. Matlab_MAT_LIBRARY
  1660. Matlab_INCLUDE_DIRS
  1661. Matlab_FOUND
  1662. Matlab_MAIN_PROGRAM
  1663. Matlab_MEXEXTENSIONS_PROG
  1664. Matlab_MEX_EXTENSION
  1665. )
  1666. endif()
  1667. cmake_policy(POP)