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