FindMatlab.cmake 71 KB

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