1
0

FindMatlab.cmake 65 KB

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