FindMatlab.cmake 70 KB

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