FindMatlab.cmake 60.8 KB
Newer Older
1 2 3
# Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#[=======================================================================[.rst:
FindMatlab
----------

Finds Matlab or Matlab Compiler Runtime (MCR) and provides Matlab tools,
libraries and compilers to CMake.

This package primary purpose is to find the libraries associated with Matlab
or the MCR in order to be able to build Matlab extensions (mex files). It
can also be used:

* to run specific commands in Matlab in case Matlab is available
* for declaring Matlab unit test
* to retrieve various information from Matlab (mex extensions, versions and
  release queries, ...)

The module supports the following components:

22 23
* ``ENG_LIBRARY`` and ``MAT_LIBRARY``: respectively the ``ENG`` and ``MAT``
  libraries of Matlab
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
* ``MAIN_PROGRAM`` the Matlab binary program. Note that this component is not
  available on the MCR version, and will yield an error if the MCR is found
  instead of the regular Matlab installation.
* ``MEX_COMPILER`` the MEX compiler.
* ``MCC_COMPILER`` the MCC compiler, included with the Matlab Compiler add-on.
* ``SIMULINK`` the Simulink environment.

.. note::

  The version given to the :command:`find_package` directive is the Matlab
  **version**, which should not be confused with the Matlab *release* name
  (eg. `R2014`).
  The :command:`matlab_get_version_from_release_name` and
  :command:`matlab_get_release_name_from_version` provide a mapping
  between the release name and the version.

The variable :variable:`Matlab_ROOT_DIR` may be specified in order to give
the path of the desired Matlab version. Otherwise, the behaviour is platform
specific:

* Windows: The installed versions of Matlab/MCR are retrieved from the
  Windows registry
* OS X: The installed versions of Matlab/MCR are given by the MATLAB
  default installation paths in ``/Application``. If no such application is
  found, it falls back to the one that might be accessible from the ``PATH``.
* Unix: The desired Matlab should be accessible from the ``PATH``. This does
  not work for MCR installation and :variable:`Matlab_ROOT_DIR` should be
  specified on this platform.

Additional information is provided when :variable:`MATLAB_FIND_DEBUG` is set.
When a Matlab/MCR installation is found automatically and the ``MATLAB_VERSION``
is not given, the version is queried from Matlab directly (on Windows this
may pop up a Matlab window) or from the MCR installation.

The mapping of the release names and the version of Matlab is performed by
defining pairs (name, version).  The variable
:variable:`MATLAB_ADDITIONAL_VERSIONS` may be provided before the call to
the :command:`find_package` in order to handle additional versions.

A Matlab scripts can be added to the set of tests using the
:command:`matlab_add_unit_test`. By default, the Matlab unit test framework
will be used (>= 2013a) to run this script, but regular ``.m`` files
returning an exit code can be used as well (0 indicating a success).

Module Input Variables
^^^^^^^^^^^^^^^^^^^^^^

Users or projects may set the following variables to configure the module
behaviour:

:variable:`Matlab_ROOT_DIR`
  the root of the Matlab installation.
:variable:`MATLAB_FIND_DEBUG`
  outputs debug information
:variable:`MATLAB_ADDITIONAL_VERSIONS`
  additional versions of Matlab for the automatic retrieval of the installed
  versions.

Variables defined by the module
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Result variables
""""""""""""""""

``Matlab_FOUND``
  ``TRUE`` if the Matlab installation is found, ``FALSE``
  otherwise. All variable below are defined if Matlab is found.
``Matlab_ROOT_DIR``
  the final root of the Matlab installation determined by the FindMatlab
  module.
``Matlab_MAIN_PROGRAM``
  the Matlab binary program. Available only if the component ``MAIN_PROGRAM``
  is given in the :command:`find_package` directive.
``Matlab_INCLUDE_DIRS``
 the path of the Matlab libraries headers
``Matlab_MEX_LIBRARY``
  library for mex, always available.
``Matlab_MX_LIBRARY``
102
  mx library of Matlab (arrays), always available.
103 104 105 106 107 108 109
``Matlab_ENG_LIBRARY``
  Matlab engine library. Available only if the component ``ENG_LIBRARY``
  is requested.
``Matlab_MAT_LIBRARY``
  Matlab matrix library. Available only if the component ``MAT_LIBRARY``
  is requested.
``Matlab_ENGINE_LIBRARY``
110
  Matlab C++ engine library, always available for R2018a and newer.
111
``Matlab_DATAARRAY_LIBRARY``
112
  Matlab C++ data array library, always available for R2018a and newer.
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
``Matlab_LIBRARIES``
  the whole set of libraries of Matlab
``Matlab_MEX_COMPILER``
  the mex compiler of Matlab. Currently not used.
  Available only if the component ``MEX_COMPILER`` is requested.
``Matlab_MCC_COMPILER``
  the mcc compiler of Matlab. Included with the Matlab Compiler add-on.
  Available only if the component ``MCC_COMPILER`` is requested.

Cached variables
""""""""""""""""

``Matlab_MEX_EXTENSION``
  the extension of the mex files for the current platform (given by Matlab).
``Matlab_ROOT_DIR``
  the location of the root of the Matlab installation found. If this value
  is changed by the user, the result variables are recomputed.

Provided macros
^^^^^^^^^^^^^^^

:command:`matlab_get_version_from_release_name`
  returns the version from the release name
:command:`matlab_get_release_name_from_version`
  returns the release name from the Matlab version

Provided functions
^^^^^^^^^^^^^^^^^^

:command:`matlab_add_mex`
  adds a target compiling a MEX file.
:command:`matlab_add_unit_test`
  adds a Matlab unit test file as a test to the project.
:command:`matlab_extract_all_installed_versions_from_registry`
  parses the registry for all Matlab versions. Available on Windows only.
  The part of the registry parsed is dependent on the host processor
:command:`matlab_get_all_valid_matlab_roots_from_registry`
  returns all the possible Matlab or MCR paths, according to a previously
  given list. Only the existing/accessible paths are kept. This is mainly
  useful for the searching all possible Matlab installation.
:command:`matlab_get_mex_suffix`
  returns the suffix to be used for the mex files
  (platform/architecture dependent)
:command:`matlab_get_version_from_matlab_run`
  returns the version of Matlab/MCR, given the full directory of the Matlab/MCR
  installation path.


Known issues
^^^^^^^^^^^^

**Symbol clash in a MEX target**
  By default, every symbols inside a MEX
  file defined with the command :command:`matlab_add_mex` have hidden
  visibility, except for the entry point. This is the default behaviour of
  the MEX compiler, which lowers the risk of symbol collision between the
  libraries shipped with Matlab, and the libraries to which the MEX file is
  linking to. This is also the default on Windows platforms.

  However, this is not sufficient in certain case, where for instance your
  MEX file is linking against libraries that are already loaded by Matlab,
  even if those libraries have different SONAMES.
  A possible solution is to hide the symbols of the libraries to which the
  MEX target is linking to. This can be achieved in GNU GCC compilers with
  the linker option ``-Wl,--exclude-libs,ALL``.

**Tests using GPU resources**
  in case your MEX file is using the GPU and
  in order to be able to run unit tests on this MEX file, the GPU resources
  should be properly released by Matlab. A possible solution is to make
  Matlab aware of the use of the GPU resources in the session, which can be
  performed by a command such as ``D = gpuDevice()`` at the beginning of
  the test script (or via a fixture).


Reference
^^^^^^^^^

.. variable:: Matlab_ROOT_DIR

   The root folder of the Matlab installation. If set before the call to
   :command:`find_package`, the module will look for the components in that
   path. If not set, then an automatic search of Matlab
   will be performed. If set, it should point to a valid version of Matlab.

.. variable:: MATLAB_FIND_DEBUG

   If set, the lookup of Matlab and the intermediate configuration steps are
   outputted to the console.

.. variable:: MATLAB_ADDITIONAL_VERSIONS

  If set, specifies additional versions of Matlab that may be looked for.
  The variable should be a list of strings, organised by pairs of release
  name and versions, such as follows::

    set(MATLAB_ADDITIONAL_VERSIONS
        "release_name1=corresponding_version1"
        "release_name2=corresponding_version2"
        ...
        )

  Example::

    set(MATLAB_ADDITIONAL_VERSIONS
        "R2013b=8.2"
        "R2013a=8.1"
        "R2012b=8.0")

  The order of entries in this list matters when several versions of
  Matlab are installed. The priority is set according to the ordering in
  this list.
#]=======================================================================]
Bill Hoffman's avatar
Bill Hoffman committed
226

227 228
set(_FindMatlab_SELF_DIR "${CMAKE_CURRENT_LIST_DIR}")

229
include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
230
include(CheckCXXCompilerFlag)
231
include(CheckCCompilerFlag)
232 233 234 235 236 237 238 239 240


# The currently supported versions. Other version can be added by the user by
# providing MATLAB_ADDITIONAL_VERSIONS
if(NOT MATLAB_ADDITIONAL_VERSIONS)
  set(MATLAB_ADDITIONAL_VERSIONS)
endif()

set(MATLAB_VERSIONS_MAPPING
241 242
  "R2018b=9.5"
  "R2018a=9.4"
243
  "R2017b=9.3"
244
  "R2017a=9.2"
245
  "R2016b=9.1"
246
  "R2016a=9.0"
247
  "R2015b=8.6"
248 249
  "R2015a=8.5"
  "R2014b=8.4"
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
  "R2014a=8.3"
  "R2013b=8.2"
  "R2013a=8.1"
  "R2012b=8.0"
  "R2012a=7.14"
  "R2011b=7.13"
  "R2011a=7.12"
  "R2010b=7.11"

  ${MATLAB_ADDITIONAL_VERSIONS}
  )


# temporary folder for all Matlab runs
set(_matlab_temporary_folder ${CMAKE_BINARY_DIR}/Matlab)

if(NOT EXISTS "${_matlab_temporary_folder}")
  file(MAKE_DIRECTORY "${_matlab_temporary_folder}")
endif()

270 271 272 273 274
#[=======================================================================[.rst:
.. command:: matlab_get_version_from_release_name

  Returns the version of Matlab (17.58) from a release name (R2017k)
#]=======================================================================]
275
macro(matlab_get_version_from_release_name release_name version_name)
276 277 278 279 280 281

  string(REGEX MATCHALL "${release_name}=([0-9]+\\.?[0-9]*)" _matched ${MATLAB_VERSIONS_MAPPING})

  set(${version_name} "")
  if(NOT _matched STREQUAL "")
    set(${version_name} ${CMAKE_MATCH_1})
282
  else()
283
    message(WARNING "[MATLAB] The release name ${release_name} is not registered")
284 285 286 287 288 289 290 291 292
  endif()
  unset(_matched)

endmacro()





293 294 295 296 297
#[=======================================================================[.rst:
.. command:: matlab_get_release_name_from_version

  Returns the release name (R2017k) from the version of Matlab (17.58)
#]=======================================================================]
298
macro(matlab_get_release_name_from_version version release_name)
299 300 301 302 303 304 305 306 307 308 309 310 311

  set(${release_name} "")
  foreach(_var IN LISTS MATLAB_VERSIONS_MAPPING)
    string(REGEX MATCHALL "(.+)=${version}" _matched ${_var})
    if(NOT _matched STREQUAL "")
      set(${release_name} ${CMAKE_MATCH_1})
      break()
    endif()
  endforeach(_var)

  unset(_var)
  unset(_matched)
  if(${release_name} STREQUAL "")
312
    message(WARNING "[MATLAB] The version ${version} is not registered")
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
  endif()

endmacro()





# extracts all the supported release names (R2017k...) of Matlab
# internal use
macro(matlab_get_supported_releases list_releases)
  set(${list_releases})
  foreach(_var IN LISTS MATLAB_VERSIONS_MAPPING)
    string(REGEX MATCHALL "(.+)=([0-9]+\\.?[0-9]*)" _matched ${_var})
    if(NOT _matched STREQUAL "")
      list(APPEND ${list_releases} ${CMAKE_MATCH_1})
    endif()
    unset(_matched)
    unset(CMAKE_MATCH_1)
  endforeach(_var)
  unset(_var)
endmacro()



# extracts all the supported versions of Matlab
# internal use
macro(matlab_get_supported_versions list_versions)
  set(${list_versions})
  foreach(_var IN LISTS MATLAB_VERSIONS_MAPPING)
    string(REGEX MATCHALL "(.+)=([0-9]+\\.?[0-9]*)" _matched ${_var})
    if(NOT _matched STREQUAL "")
      list(APPEND ${list_versions} ${CMAKE_MATCH_2})
    endif()
    unset(_matched)
    unset(CMAKE_MATCH_1)
  endforeach(_var)
  unset(_var)
endmacro()


354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
#[=======================================================================[.rst:
.. command:: matlab_extract_all_installed_versions_from_registry

  This function parses the registry and founds the Matlab versions that are
  installed. The found versions are returned in `matlab_versions`.
  Set `win64` to `TRUE` if the 64 bit version of Matlab should be looked for
  The returned list contains all versions under
  ``HKLM\\SOFTWARE\\Mathworks\\MATLAB`` and
  ``HKLM\\SOFTWARE\\Mathworks\\MATLAB Runtime`` or an empty list in case an
  error occurred (or nothing found).

  .. note::

    Only the versions are provided. No check is made over the existence of the
    installation referenced in the registry,

#]=======================================================================]
371 372 373
function(matlab_extract_all_installed_versions_from_registry win64 matlab_versions)

  if(NOT CMAKE_HOST_WIN32)
374
    message(FATAL_ERROR "[MATLAB] This macro can only be called by a windows host (call to reg.exe)")
375 376
  endif()

377
  if(${win64} AND CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "64")
378 379 380 381 382
    set(APPEND_REG "/reg:64")
  else()
    set(APPEND_REG "/reg:32")
  endif()

383
  set(matlabs_from_registry)
384

385
  foreach(_installation_type IN ITEMS "MATLAB" "MATLAB Runtime")
386

387 388 389 390 391 392 393 394 395
    # /reg:64 should be added on 64 bits capable OSs in order to enable the
    # redirection of 64 bits applications
    execute_process(
      COMMAND reg query HKEY_LOCAL_MACHINE\\SOFTWARE\\Mathworks\\${_installation_type} /f * /k ${APPEND_REG}
      RESULT_VARIABLE resultMatlab
      OUTPUT_VARIABLE varMatlab
      ERROR_VARIABLE errMatlab
      INPUT_FILE NUL
      )
396 397


398
    if(${resultMatlab} EQUAL 0)
399

400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
      string(
        REGEX MATCHALL "MATLAB\\\\([0-9]+(\\.[0-9]+)?)"
        matlab_versions_regex ${varMatlab})

      foreach(match IN LISTS matlab_versions_regex)
        string(
          REGEX MATCH "MATLAB\\\\(([0-9]+)(\\.([0-9]+))?)"
          current_match ${match})

        set(_matlab_current_version ${CMAKE_MATCH_1})
        set(current_matlab_version_major ${CMAKE_MATCH_2})
        set(current_matlab_version_minor ${CMAKE_MATCH_4})
        if(NOT current_matlab_version_minor)
          set(current_matlab_version_minor "0")
        endif()
415

416 417 418
        list(APPEND matlabs_from_registry ${_matlab_current_version})
        unset(_matlab_current_version)
      endforeach()
419

420 421
    endif()
  endforeach()
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478

  if(matlabs_from_registry)
    list(REMOVE_DUPLICATES matlabs_from_registry)
    list(SORT matlabs_from_registry)
    list(REVERSE matlabs_from_registry)
  endif()

  set(${matlab_versions} ${matlabs_from_registry} PARENT_SCOPE)

endfunction()



# (internal)
macro(extract_matlab_versions_from_registry_brute_force matlab_versions)
  # get the supported versions
  set(matlab_supported_versions)
  matlab_get_supported_versions(matlab_supported_versions)


  # this is a manual population of the versions we want to look for
  # this can be done as is, but preferably with the call to
  # matlab_get_supported_versions and variable

  # populating the versions we want to look for
  # set(matlab_supported_versions)

  # # Matlab 7
  # set(matlab_major 7)
  # foreach(current_matlab_minor RANGE 4 20)
    # list(APPEND matlab_supported_versions "${matlab_major}.${current_matlab_minor}")
  # endforeach(current_matlab_minor)

  # # Matlab 8
  # set(matlab_major 8)
  # foreach(current_matlab_minor RANGE 0 5)
    # list(APPEND matlab_supported_versions "${matlab_major}.${current_matlab_minor}")
  # endforeach(current_matlab_minor)

  # # taking into account the possible additional versions provided by the user
  # if(DEFINED MATLAB_ADDITIONAL_VERSIONS)
    # list(APPEND matlab_supported_versions MATLAB_ADDITIONAL_VERSIONS)
  # endif()

  # we order from more recent to older
  if(matlab_supported_versions)
    list(REMOVE_DUPLICATES matlab_supported_versions)
    list(SORT matlab_supported_versions)
    list(REVERSE matlab_supported_versions)
  endif()

  set(${matlab_versions} ${matlab_supported_versions})
endmacro()




479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
#[=======================================================================[.rst:
.. command:: matlab_get_all_valid_matlab_roots_from_registry

  Populates the Matlab root with valid versions of Matlab or
  Matlab Runtime (MCR).
  The returned matlab_roots is organized in triplets
  ``(type,version_number,matlab_root_path)``, where ``type``
  indicates either ``MATLAB`` or ``MCR``.

  ::

    matlab_get_all_valid_matlab_roots_from_registry(
        matlab_versions
        matlab_roots)

  ``matlab_versions``
    the versions of each of the Matlab or MCR installations
  ``matlab_roots``
    the location of each of the Matlab or MCR installations
#]=======================================================================]
499 500 501 502 503 504 505
function(matlab_get_all_valid_matlab_roots_from_registry matlab_versions matlab_roots)

  # The matlab_versions comes either from
  # extract_matlab_versions_from_registry_brute_force or
  # matlab_extract_all_installed_versions_from_registry.

  set(_matlab_roots_list )
506
  # check for Matlab installations
507 508 509 510 511 512 513
  foreach(_matlab_current_version ${matlab_versions})
    get_filename_component(
      current_MATLAB_ROOT
      "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MathWorks\\MATLAB\\${_matlab_current_version};MATLABROOT]"
      ABSOLUTE)

    if(EXISTS ${current_MATLAB_ROOT})
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
      list(APPEND _matlab_roots_list "MATLAB" ${_matlab_current_version} ${current_MATLAB_ROOT})
    endif()

  endforeach()

  # Check for MCR installations
  foreach(_matlab_current_version ${matlab_versions})
    get_filename_component(
      current_MATLAB_ROOT
      "[HKEY_LOCAL_MACHINE\\SOFTWARE\\MathWorks\\MATLAB Runtime\\${_matlab_current_version};MATLABROOT]"
      ABSOLUTE)

    # remove the dot
    string(REPLACE "." "" _matlab_current_version_without_dot "${_matlab_current_version}")

    if(EXISTS ${current_MATLAB_ROOT})
      list(APPEND _matlab_roots_list "MCR" ${_matlab_current_version} "${current_MATLAB_ROOT}/v${_matlab_current_version_without_dot}")
531 532
    endif()

533
  endforeach()
534 535 536
  set(${matlab_roots} ${_matlab_roots_list} PARENT_SCOPE)
endfunction()

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
#[=======================================================================[.rst:
.. command:: matlab_get_mex_suffix

  Returns the extension of the mex files (the suffixes).
  This function should not be called before the appropriate Matlab root has
  been found.

  ::

    matlab_get_mex_suffix(
        matlab_root
        mex_suffix)

  ``matlab_root``
    the root of the Matlab/MCR installation
  ``mex_suffix``
    the variable name in which the suffix will be returned.
#]=======================================================================]
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
function(matlab_get_mex_suffix matlab_root mex_suffix)

  # todo setup the extension properly. Currently I do not know if this is
  # sufficient for all win32 distributions.
  # there is also CMAKE_EXECUTABLE_SUFFIX that could be tweaked
  set(mexext_suffix "")
  if(WIN32)
    list(APPEND mexext_suffix ".bat")
  endif()

  # we first try without suffix, since cmake does not understand a list with
  # one empty string element
  find_program(
    Matlab_MEXEXTENSIONS_PROG
    NAMES mexext
    PATHS ${matlab_root}/bin
    DOC "Matlab MEX extension provider"
    NO_DEFAULT_PATH
  )

  foreach(current_mexext_suffix IN LISTS mexext_suffix)
    if(NOT DEFINED Matlab_MEXEXTENSIONS_PROG OR NOT Matlab_MEXEXTENSIONS_PROG)
      # this call should populate the cache automatically
      find_program(
        Matlab_MEXEXTENSIONS_PROG
        "mexext${current_mexext_suffix}"
        PATHS ${matlab_root}/bin
        DOC "Matlab MEX extension provider"
        NO_DEFAULT_PATH
      )
    endif()
  endforeach(current_mexext_suffix)
587 588 589
  if(MATLAB_FIND_DEBUG)
    message(STATUS "[MATLAB] Determining mex files extensions from '${matlab_root}/bin' with program '${Matlab_MEXEXTENSIONS_PROG}'")
  endif()
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608

  # the program has been found?
  if((NOT Matlab_MEXEXTENSIONS_PROG) OR (NOT EXISTS ${Matlab_MEXEXTENSIONS_PROG}))
    if(MATLAB_FIND_DEBUG)
      message(WARNING "[MATLAB] Cannot found mexext program. Matlab root is ${matlab_root}")
    endif()
    unset(Matlab_MEXEXTENSIONS_PROG CACHE)
    return()
  endif()

  set(_matlab_mex_extension)

  set(devnull)
  if(UNIX)
    set(devnull INPUT_FILE /dev/null)
  elseif(WIN32)
    set(devnull INPUT_FILE NUL)
  endif()

luz.paz's avatar
luz.paz committed
609
  # this is the preferred way. If this does not work properly (eg. MCR on Windows), then we use our own knowledge
610 611 612
  execute_process(
    COMMAND ${Matlab_MEXEXTENSIONS_PROG}
    OUTPUT_VARIABLE _matlab_mex_extension
613
    #RESULT_VARIABLE _matlab_mex_extension_call
614 615
    ERROR_VARIABLE _matlab_mex_extension_error
    ${devnull})
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631

  if(NOT "${_matlab_mex_extension_error}" STREQUAL "")
    if(WIN32)
      # this is only for intel architecture
      if(CMAKE_SIZEOF_VOID_P EQUAL 8)
        set(_matlab_mex_extension "mexw64")
      else()
        set(_matlab_mex_extension "mexw32")
      endif()
    endif()
  endif()

  string(STRIP "${_matlab_mex_extension}"  _matlab_mex_extension)
  if(MATLAB_FIND_DEBUG)
    message(STATUS "[MATLAB] '${Matlab_MEXEXTENSIONS_PROG}' : returned '${_matlab_mex_extension_call}', determined extension '${_matlab_mex_extension}' and error string is '${_matlab_mex_extension_error}'")
  endif()
632 633 634 635 636 637 638 639

  unset(Matlab_MEXEXTENSIONS_PROG CACHE)
  set(${mex_suffix} ${_matlab_mex_extension} PARENT_SCOPE)
endfunction()




640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
#[=======================================================================[.rst:
.. command:: matlab_get_version_from_matlab_run

  This function runs Matlab program specified on arguments and extracts its
  version. If the path provided for the Matlab installation points to an MCR
  installation, the version is extracted from the installed files.

  ::

    matlab_get_version_from_matlab_run(
        matlab_binary_path
        matlab_list_versions)

  ``matlab_binary_path``
    the location of the `matlab` binary executable
  ``matlab_list_versions``
    the version extracted from Matlab
#]=======================================================================]
658 659 660 661 662 663 664 665 666 667 668
function(matlab_get_version_from_matlab_run matlab_binary_program matlab_list_versions)

  set(${matlab_list_versions} "" PARENT_SCOPE)

  if(MATLAB_FIND_DEBUG)
    message(STATUS "[MATLAB] Determining the version of Matlab from ${matlab_binary_program}")
  endif()

  if(EXISTS "${_matlab_temporary_folder}/matlabVersionLog.cmaketmp")
    if(MATLAB_FIND_DEBUG)
      message(STATUS "[MATLAB] Removing previous ${_matlab_temporary_folder}/matlabVersionLog.cmaketmp file")
669
    endif()
670 671 672 673 674 675 676 677 678 679
    file(REMOVE "${_matlab_temporary_folder}/matlabVersionLog.cmaketmp")
  endif()


  # the log file is needed since on windows the command executes in a new
  # window and it is not possible to get back the answer of Matlab
  # the -wait command is needed on windows, otherwise the call returns
  # immediately after the program launches itself.
  if(WIN32)
    set(_matlab_additional_commands "-wait")
680
  endif()
681 682 683 684 685 686 687 688

  set(devnull)
  if(UNIX)
    set(devnull INPUT_FILE /dev/null)
  elseif(WIN32)
    set(devnull INPUT_FILE NUL)
  endif()

689
  # timeout set to 120 seconds, in case it does not start
690 691 692 693 694 695 696 697
  # note as said before OUTPUT_VARIABLE cannot be used in a platform
  # independent manner however, not setting it would flush the output of Matlab
  # in the current console (unix variant)
  execute_process(
    COMMAND "${matlab_binary_program}" -nosplash -nojvm ${_matlab_additional_commands} -logfile "matlabVersionLog.cmaketmp" -nodesktop -nodisplay -r "version, exit"
    OUTPUT_VARIABLE _matlab_version_from_cmd_dummy
    RESULT_VARIABLE _matlab_result_version_call
    ERROR_VARIABLE _matlab_result_version_call_error
698
    TIMEOUT 120
699 700
    WORKING_DIRECTORY "${_matlab_temporary_folder}"
    ${devnull}
Bill Hoffman's avatar
Bill Hoffman committed
701
    )
702

703 704 705 706 707 708 709
  if("${_matlab_result_version_call}" MATCHES "timeout")
    if(MATLAB_FIND_DEBUG)
      message(WARNING "[MATLAB] Unable to determine the version of Matlab."
        " Matlab call timed out after 120 seconds.")
    endif()
    return()
  endif()
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727

  if(${_matlab_result_version_call})
    if(MATLAB_FIND_DEBUG)
      message(WARNING "[MATLAB] Unable to determine the version of Matlab. Matlab call returned with error ${_matlab_result_version_call}.")
    endif()
    return()
  elseif(NOT EXISTS "${_matlab_temporary_folder}/matlabVersionLog.cmaketmp")
    if(MATLAB_FIND_DEBUG)
      message(WARNING "[MATLAB] Unable to determine the version of Matlab. The log file does not exist.")
    endif()
    return()
  endif()

  # if successful, read back the log
  file(READ "${_matlab_temporary_folder}/matlabVersionLog.cmaketmp" _matlab_version_from_cmd)
  file(REMOVE "${_matlab_temporary_folder}/matlabVersionLog.cmaketmp")

  set(index -1)
728
  string(FIND "${_matlab_version_from_cmd}" "ans" index)
729 730 731 732 733 734 735 736 737
  if(index EQUAL -1)

    if(MATLAB_FIND_DEBUG)
      message(WARNING "[MATLAB] Cannot find the version of Matlab returned by the run.")
    endif()

  else()
    set(matlab_list_of_all_versions_tmp)

738
    string(SUBSTRING "${_matlab_version_from_cmd}" ${index} -1 substring_ans)
739
    string(
740
      REGEX MATCHALL "ans[\r\n\t ]*=[\r\n\t ]*'?([0-9]+(\\.[0-9]+)?)"
741 742 743 744
      matlab_versions_regex
      ${substring_ans})
    foreach(match IN LISTS matlab_versions_regex)
      string(
745
        REGEX MATCH "ans[\r\n\t ]*=[\r\n\t ]*'?(([0-9]+)(\\.([0-9]+))?)"
746 747 748 749 750 751 752 753 754 755 756 757 758
        current_match ${match})

      list(APPEND matlab_list_of_all_versions_tmp ${CMAKE_MATCH_1})
    endforeach()
    if(matlab_list_of_all_versions_tmp)
      list(REMOVE_DUPLICATES matlab_list_of_all_versions_tmp)
    endif()
    set(${matlab_list_versions} ${matlab_list_of_all_versions_tmp} PARENT_SCOPE)

  endif()

endfunction()

759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
#[=======================================================================[.rst:
.. command:: matlab_add_unit_test

  Adds a Matlab unit test to the test set of cmake/ctest.
  This command requires the component ``MAIN_PROGRAM`` and hence is not
  available for an MCR installation.

  The unit test uses the Matlab unittest framework (default, available
  starting Matlab 2013b+) except if the option ``NO_UNITTEST_FRAMEWORK``
  is given.

  The function expects one Matlab test script file to be given.
  In the case ``NO_UNITTEST_FRAMEWORK`` is given, the unittest script file
  should contain the script to be run, plus an exit command with the exit
  value. This exit value will be passed to the ctest framework (0 success,
  non 0 failure). Additional arguments accepted by :command:`add_test` can be
  passed through ``TEST_ARGS`` (eg. ``CONFIGURATION <config> ...``).

  ::

    matlab_add_unit_test(
        NAME <name>
        UNITTEST_FILE matlab_file_containing_unittest.m
        [CUSTOM_TEST_COMMAND matlab_command_to_run_as_test]
        [UNITTEST_PRECOMMAND matlab_command_to_run]
        [TIMEOUT timeout]
        [ADDITIONAL_PATH path1 [path2 ...]]
        [MATLAB_ADDITIONAL_STARTUP_OPTIONS option1 [option2 ...]]
        [TEST_ARGS arg1 [arg2 ...]]
        [NO_UNITTEST_FRAMEWORK]
        )

  The function arguments are:

  ``NAME``
    name of the unittest in ctest.
  ``UNITTEST_FILE``
    the matlab unittest file. Its path will be automatically
    added to the Matlab path.
  ``CUSTOM_TEST_COMMAND``
    Matlab script command to run as the test.
    If this is not set, then the following is run:
    ``runtests('matlab_file_name'), exit(max([ans(1,:).Failed]))``
    where ``matlab_file_name`` is the ``UNITTEST_FILE`` without the extension.
  ``UNITTEST_PRECOMMAND``
    Matlab script command to be ran before the file
    containing the test (eg. GPU device initialisation based on CMake
    variables).
  ``TIMEOUT``
    the test timeout in seconds. Defaults to 180 seconds as the
    Matlab unit test may hang.
  ``ADDITIONAL_PATH``
    a list of paths to add to the Matlab path prior to
    running the unit test.
  ``MATLAB_ADDITIONAL_STARTUP_OPTIONS``
    a list of additional option in order
    to run Matlab from the command line.
    ``-nosplash -nodesktop -nodisplay`` are always added.
  ``TEST_ARGS``
    Additional options provided to the add_test command. These
    options are added to the default options (eg. "CONFIGURATIONS Release")
  ``NO_UNITTEST_FRAMEWORK``
    when set, indicates that the test should not
    use the unittest framework of Matlab (available for versions >= R2013a).
  ``WORKING_DIRECTORY``
    This will be the working directory for the test. If specified it will
    also be the output directory used for the log file of the test run.
    If not specified the temporary directory ``${CMAKE_BINARY_DIR}/Matlab`` will
    be used as the working directory and the log location.

#]=======================================================================]
830 831 832 833 834 835 836
function(matlab_add_unit_test)

  if(NOT Matlab_MAIN_PROGRAM)
    message(FATAL_ERROR "[MATLAB] This functionality needs the MAIN_PROGRAM component (not default)")
  endif()

  set(options NO_UNITTEST_FRAMEWORK)
837 838
  set(oneValueArgs NAME UNITTEST_FILE TIMEOUT WORKING_DIRECTORY
    UNITTEST_PRECOMMAND CUSTOM_TEST_COMMAND)
839 840 841
  set(multiValueArgs ADDITIONAL_PATH MATLAB_ADDITIONAL_STARTUP_OPTIONS TEST_ARGS)

  set(prefix _matlab_unittest_prefix)
842
  cmake_parse_arguments(PARSE_ARGV 0 ${prefix} "${options}" "${oneValueArgs}" "${multiValueArgs}" )
843 844 845 846 847 848 849

  if(NOT ${prefix}_NAME)
    message(FATAL_ERROR "[MATLAB] The Matlab test name cannot be empty")
  endif()

  add_test(NAME ${${prefix}_NAME}
           COMMAND ${CMAKE_COMMAND}
850 851 852 853 854 855 856
            "-Dtest_name=${${prefix}_NAME}"
            "-Dadditional_paths=${${prefix}_ADDITIONAL_PATH}"
            "-Dtest_timeout=${${prefix}_TIMEOUT}"
            "-Doutput_directory=${_matlab_temporary_folder}"
            "-Dworking_directory=${${prefix}_WORKING_DIRECTORY}"
            "-DMatlab_PROGRAM=${Matlab_MAIN_PROGRAM}"
            "-Dno_unittest_framework=${${prefix}_NO_UNITTEST_FRAMEWORK}"
857
            "-DMatlab_ADDITIONAL_STARTUP_OPTIONS=${${prefix}_MATLAB_ADDITIONAL_STARTUP_OPTIONS}"
858 859 860
            "-Dunittest_file_to_run=${${prefix}_UNITTEST_FILE}"
            "-Dcustom_Matlab_test_command=${${prefix}_CUSTOM_TEST_COMMAND}"
            "-Dcmd_to_run_before_test=${${prefix}_UNITTEST_PRECOMMAND}"
861 862 863 864 865 866 867
            -P ${_FindMatlab_SELF_DIR}/MatlabTestsRedirect.cmake
           ${${prefix}_TEST_ARGS}
           ${${prefix}_UNPARSED_ARGUMENTS}
           )
endfunction()


868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
#[=======================================================================[.rst:
.. command:: matlab_add_mex

  Adds a Matlab MEX target.
  This commands compiles the given sources with the current tool-chain in
  order to produce a MEX file. The final name of the produced output may be
  specified, as well as additional link libraries, and a documentation entry
  for the MEX file. Remaining arguments of the call are passed to the
  :command:`add_library` or :command:`add_executable` command.

  ::

     matlab_add_mex(
         NAME <name>
         [EXECUTABLE | MODULE | SHARED]
         SRC src1 [src2 ...]
         [OUTPUT_NAME output_name]
         [DOCUMENTATION file.txt]
         [LINK_TO target1 target2 ...]
887
         [R2017b | R2018a]
888 889 890 891 892 893 894 895 896
         [...]
     )

  ``NAME``
    name of the target.
  ``SRC``
    list of source files.
  ``LINK_TO``
    a list of additional link dependencies.  The target links to ``libmex``
897
    and ``libmx`` by default.
898 899 900 901 902 903 904 905 906 907
  ``OUTPUT_NAME``
    if given, overrides the default name. The default name is
    the name of the target without any prefix and
    with ``Matlab_MEX_EXTENSION`` suffix.
  ``DOCUMENTATION``
    if given, the file ``file.txt`` will be considered as
    being the documentation file for the MEX file. This file is copied into
    the same folder without any processing, with the same name as the final
    mex file, and with extension `.m`. In that case, typing ``help <name>``
    in Matlab prints the documentation contained in this file.
908 909 910 911 912 913
  ``R2017b`` or ``R2018a`` may be given to specify the version of the C API
    to use: ``R2017b`` specifies the traditional (separate complex) C API,
    and corresponds to the ``-R2017b`` flag for the `mex` command. ``R2018a``
    specifies the new interleaved complex C API, and corresponds to the
    ``-R2018a`` flag for the `mex` command. Ignored if MATLAB version prior
    to R2018a. Defaults to ``R2017b``.
914 915 916 917 918 919 920 921 922 923 924 925 926
  ``MODULE`` or ``SHARED`` may be given to specify the type of library to be
    created. ``EXECUTABLE`` may be given to create an executable instead of
    a library. If no type is given explicitly, the type is ``SHARED``.

  The documentation file is not processed and should be in the following
  format:

  ::

    % This is the documentation
    function ret = mex_target_output_name(input1)

#]=======================================================================]
927
function(matlab_add_mex)
928 929 930 931

  if(NOT WIN32)
    # we do not need all this on Windows
    # pthread options
932 933 934 935 936
    if(CMAKE_CXX_COMPILER_LOADED)
      check_cxx_compiler_flag(-pthread HAS_MINUS_PTHREAD)
    elseif(CMAKE_C_COMPILER_LOADED)
      check_c_compiler_flag(-pthread HAS_MINUS_PTHREAD)
    endif()
937 938 939 940 941 942
    # we should use try_compile instead, the link flags are discarded from
    # this compiler_flag function.
    #check_cxx_compiler_flag(-Wl,--exclude-libs,ALL HAS_SYMBOL_HIDING_CAPABILITY)

  endif()

943
  set(options EXECUTABLE MODULE SHARED R2017b R2018a)
944 945 946 947 948 949 950 951 952 953 954 955 956 957
  set(oneValueArgs NAME DOCUMENTATION OUTPUT_NAME)
  set(multiValueArgs LINK_TO SRC)

  set(prefix _matlab_addmex_prefix)
  cmake_parse_arguments(${prefix} "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} )

  if(NOT ${prefix}_NAME)
    message(FATAL_ERROR "[MATLAB] The MEX target name cannot be empty")
  endif()

  if(NOT ${prefix}_OUTPUT_NAME)
    set(${prefix}_OUTPUT_NAME ${${prefix}_NAME})
  endif()

958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
  if(NOT ${Matlab_VERSION_STRING} VERSION_LESS "9.1") # For 9.1 (R2016b) and newer, add version source file
    # TODO: check the file extensions in ${${prefix}_SRC} to see if they're C or C++ files
    # Currently, the C and C++ versions of the version files are identical, so this doesn't matter.
    set(MEX_VERSION_FILE "${Matlab_ROOT_DIR}/extern/version/c_mexapi_version.c")
    #set(MEX_VERSION_FILE "${Matlab_ROOT_DIR}/extern/version/cpp_mexapi_version.cpp")
  endif()

  if(NOT ${Matlab_VERSION_STRING} VERSION_LESS "9.4") # For 9.4 (R2018a) and newer, add API macro
    if(${${prefix}_R2018a})
      set(MEX_API_MACRO "MATLAB_DEFAULT_RELEASE=R2018a")
    else()
      set(MEX_API_MACRO "MATLAB_DEFAULT_RELEASE=R2017b")
    endif()
  endif()

973 974
  if(${prefix}_EXECUTABLE)
    add_executable(${${prefix}_NAME}
975
      ${${prefix}_SRC}
976
      ${MEX_VERSION_FILE}
977 978
      ${${prefix}_DOCUMENTATION}
      ${${prefix}_UNPARSED_ARGUMENTS})
979 980 981 982 983 984 985 986 987 988
  else()
    if(${prefix}_MODULE)
      set(type MODULE)
    else()
      set(type SHARED)
    endif()

    add_library(${${prefix}_NAME}
      ${type}
      ${${prefix}_SRC}
989
      ${MEX_VERSION_FILE}
990 991 992 993
      ${${prefix}_DOCUMENTATION}
      ${${prefix}_UNPARSED_ARGUMENTS})
  endif()

994 995
  target_include_directories(${${prefix}_NAME} PRIVATE ${Matlab_INCLUDE_DIRS})

996 997
  if(Matlab_HAS_CPP_API)
    target_link_libraries(${${prefix}_NAME} ${Matlab_ENGINE_LIBRARY} ${Matlab_DATAARRAY_LIBRARY})
998 999
  endif()

1000
  target_link_libraries(${${prefix}_NAME} ${Matlab_MEX_LIBRARY} ${Matlab_MX_LIBRARY} ${${prefix}_LINK_TO})
1001 1002 1003 1004 1005 1006
  set_target_properties(${${prefix}_NAME}
      PROPERTIES
        PREFIX ""
        OUTPUT_NAME ${${prefix}_OUTPUT_NAME}
        SUFFIX ".${Matlab_MEX_EXTENSION}")

1007
  target_compile_definitions(${${prefix}_NAME} PRIVATE ${MEX_API_MACRO} MATLAB_MEX_FILE)
1008 1009 1010 1011 1012 1013 1014 1015

  # documentation
  if(NOT ${${prefix}_DOCUMENTATION} STREQUAL "")
    get_target_property(output_name ${${prefix}_NAME} OUTPUT_NAME)
    add_custom_command(
      TARGET ${${prefix}_NAME}
      PRE_BUILD
      COMMAND ${CMAKE_COMMAND} -E copy_if_different ${${prefix}_DOCUMENTATION} $<TARGET_FILE_DIR:${${prefix}_NAME}>/${output_name}.m
1016
      COMMENT "[MATLAB] Copy ${${prefix}_NAME} documentation file into the output folder"
Bill Hoffman's avatar
Bill Hoffman committed
1017
    )
1018 1019 1020
  endif() # documentation

  # entry point in the mex file + taking care of visibility and symbol clashes.
1021
  if(WIN32)
1022

1023 1024
    if (MSVC)

1025
      set(_link_flags "${_link_flags} /EXPORT:mexFunction")
1026
      if(NOT ${Matlab_VERSION_STRING} VERSION_LESS "9.1") # For 9.1 (R2016b) and newer, export version
1027
        set(_link_flags "${_link_flags} /EXPORT:mexfilerequiredapiversion")
1028 1029 1030
      endif()

      if(Matlab_HAS_CPP_API)
1031
        set(_link_flags "${_link_flags} /EXPORT:mexCreateMexFunction /EXPORT:mexDestroyMexFunction /EXPORT:mexFunctionAdapter")
1032 1033 1034 1035 1036 1037
        #TODO: Is this necessary?
      endif()

      set_property(TARGET ${${prefix}_NAME} APPEND PROPERTY LINK_FLAGS ${_link_flags})

    endif() # TODO: what if there's a different compiler on Windows?
1038

1039 1040 1041
    set_target_properties(${${prefix}_NAME}
      PROPERTIES
        DEFINE_SYMBOL "DLL_EXPORT_SYM=__declspec(dllexport)")
1042

1043 1044
  else()

1045 1046 1047 1048
    if(${Matlab_VERSION_STRING} VERSION_LESS "9.1") # For versions prior to 9.1 (R2016b)
      set(_ver_map_files ${Matlab_EXTERN_LIBRARY_DIR}/mexFunction.map)
    else()                                          # For 9.1 (R2016b) and newer
      set(_ver_map_files ${Matlab_EXTERN_LIBRARY_DIR}/c_exportsmexfileversion.map)
1049 1050
    endif()

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
    if(NOT ${Matlab_VERSION_STRING} VERSION_LESS "9.5") # For 9.5 (R2018b) (and newer?)
      target_compile_options(${${prefix}_NAME} PRIVATE "-fvisibility=default")
      # This one is weird, it might be a bug in <mex.h> for R2018b. When compiling with
      # -fvisibility=hidden, the symbol `mexFunction` cannot be exported. Reading the
      # source code for <mex.h>, it seems that the preprocessor macro `MW_NEEDS_VERSION_H`
      # needs to be defined for `__attribute__ ((visibility("default")))` to be added
      # in front of the declaration of `mexFunction`. In previous versions of MATLAB this
      # was not the case, there `DLL_EXPORT_SYM` needed to be defined.
      # Adding `-fvisibility=hidden` to the `mex` command causes the build to fail.
      # TODO: Check that this is still necessary in R2019a when it comes out.
    endif()
1062

1063
    if(APPLE)
1064

1065 1066 1067 1068 1069 1070
      if(Matlab_HAS_CPP_API)
        list(APPEND _ver_map_files ${Matlab_EXTERN_LIBRARY_DIR}/cppMexFunction.map) # This one doesn't exist on Linux
        set(_link_flags "${_link_flags} -Wl,-U,_mexCreateMexFunction -Wl,-U,_mexDestroyMexFunction -Wl,-U,_mexFunctionAdapter")
        # On MacOS, the MEX command adds the above, without it the link breaks
        # because we indiscriminately use "cppMexFunction.map" even for C API MEX-files.
      endif()
Bill Hoffman's avatar
Bill Hoffman committed
1071

1072
      set(_export_flag_name -exported_symbols_list)
1073

1074
    else() # Linux
1075

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
      if(HAS_MINUS_PTHREAD)
        # Apparently, compiling with -pthread generated the proper link flags
        # and some defines at compilation
        target_compile_options(${${prefix}_NAME} PRIVATE "-pthread")
      endif()

      set(_link_flags "${_link_flags} -Wl,--as-needed")

      set(_export_flag_name --version-script)

    endif()

    foreach(_file ${_ver_map_files})
      set(_link_flags "${_link_flags} -Wl,${_export_flag_name},${_file}")
    endforeach()
1091 1092 1093 1094

    set_target_properties(${${prefix}_NAME}
      PROPERTIES
        DEFINE_SYMBOL "DLL_EXPORT_SYM=__attribute__ ((visibility (\"default\")))"
1095 1096
        LINK_FLAGS "${_link_flags}"
    ) # The `mex` command doesn't add this define. Is it necessary?
1097 1098 1099 1100 1101 1102 1103 1104 1105

  endif()

endfunction()


# (internal)
# Used to get the version of matlab, using caching. This basically transforms the
# output of the root list, with possible unknown version, to a version
1106 1107
# This can possibly run Matlab for extracting the version.
function(_Matlab_get_version_from_root matlab_root matlab_or_mcr matlab_known_version matlab_final_version)
1108

1109
  # if the version is not trivial, we query matlab (if not MCR) for that
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
  # we keep track of the location of matlab that induced this version
  #if(NOT DEFINED Matlab_PROG_VERSION_STRING_AUTO_DETECT)
  #  set(Matlab_PROG_VERSION_STRING_AUTO_DETECT "" CACHE INTERNAL "internal matlab location for the discovered version")
  #endif()

  if(NOT ${matlab_known_version} STREQUAL "NOTFOUND")
    # the version is known, we just return it
    set(${matlab_final_version} ${matlab_known_version} PARENT_SCOPE)
    set(Matlab_VERSION_STRING_INTERNAL ${matlab_known_version} CACHE INTERNAL "Matlab version (automatically determined)" FORCE)
    return()
  endif()

1122 1123 1124
  if("${matlab_or_mcr}" STREQUAL "UNKNOWN")
    if(MATLAB_FIND_DEBUG)
      message(WARNING "[MATLAB] Determining Matlab or MCR")
1125 1126
    endif()

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    if(EXISTS "${matlab_root}/appdata/version.xml")
      # we inspect the application version.xml file that contains the product information
      file(STRINGS "${matlab_root}/appdata/version.xml" productinfo_string NEWLINE_CONSUME)
      string(REGEX MATCH "<installedProductData.*displayedString=\"([a-zA-Z ]+)\".*/>"
             product_reg_match
             ${productinfo_string}
            )

      # default fallback to Matlab
      set(matlab_or_mcr "MATLAB")
      if(NOT "${CMAKE_MATCH_1}" STREQUAL "")
        string(TOLOWER "${CMAKE_MATCH_1}" product_reg_match)

        if("${product_reg_match}" STREQUAL "matlab runtime")
          set(matlab_or_mcr "MCR")
        endif()
      endif()
    endif()
1145 1146

    if(MATLAB_FIND_DEBUG)
1147
      message(WARNING "[MATLAB] '${matlab_root}' contains the '${matlab_or_mcr}'")
1148 1149 1150
    endif()
  endif()

1151 1152 1153 1154 1155 1156
  # UNKNOWN is the default behaviour in case we
  # - have an erroneous matlab_root
  # - have an initial 'UNKNOWN'
  if("${matlab_or_mcr}" STREQUAL "MATLAB" OR "${matlab_or_mcr}" STREQUAL "UNKNOWN")
    # MATLAB versions
    set(_matlab_current_program ${Matlab_MAIN_PROGRAM})
1157

1158 1159
    # do we already have a matlab program?
    if(NOT _matlab_current_program)
1160

1161 1162 1163 1164
      set(_find_matlab_options)
      if(matlab_root AND EXISTS ${matlab_root})
        set(_find_matlab_options PATHS ${matlab_root} ${matlab_root}/bin NO_DEFAULT_PATH)
      endif()
1165

1166 1167 1168 1169 1170 1171 1172
      find_program(
          _matlab_current_program
          matlab
          ${_find_matlab_options}
          DOC "Matlab main program"
        )
    endif()
1173

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    if(NOT _matlab_current_program OR NOT EXISTS ${_matlab_current_program})
      # if not found, clear the dependent variables
      if(MATLAB_FIND_DEBUG)
        message(WARNING "[MATLAB] Cannot find the main matlab program under ${matlab_root}")
      endif()
      set(Matlab_PROG_VERSION_STRING_AUTO_DETECT "" CACHE INTERNAL "internal matlab location for the discovered version" FORCE)
      set(Matlab_VERSION_STRING_INTERNAL "" CACHE INTERNAL "internal matlab location for the discovered version" FORCE)
      unset(_matlab_current_program)
      unset(_matlab_current_program CACHE)
      return()
    endif()
1185

1186 1187 1188 1189
    # full real path for path comparison
    get_filename_component(_matlab_main_real_path_tmp "${_matlab_current_program}" REALPATH)
    unset(_matlab_current_program)
    unset(_matlab_current_program CACHE)
1190

1191 1192 1193 1194 1195
    # is it the same as the previous one?
    if(_matlab_main_real_path_tmp STREQUAL Matlab_PROG_VERSION_STRING_AUTO_DETECT)
      set(${matlab_final_version} ${Matlab_VERSION_STRING_INTERNAL} PARENT_SCOPE)
      return()
    endif()
1196

1197 1198 1199 1200
    # update the location of the program
    set(Matlab_PROG_VERSION_STRING_AUTO_DETECT
        ${_matlab_main_real_path_tmp}
        CACHE INTERNAL "internal matlab location for the discovered version" FORCE)
1201

1202 1203
    set(matlab_list_of_all_versions)
    matlab_get_version_from_matlab_run("${Matlab_PROG_VERSION_STRING_AUTO_DETECT}" matlab_list_of_all_versions)
1204

1205 1206 1207 1208 1209 1210
    list(LENGTH matlab_list_of_all_versions list_of_all_versions_length)
    if(${list_of_all_versions_length} GREATER 0)
      list(GET matlab_list_of_all_versions 0 _matlab_version_tmp)
    else()
      set(_matlab_version_tmp "unknown")
    endif()
1211

1212 1213
    # set the version into the cache
    set(Matlab_VERSION_STRING_INTERNAL ${_matlab_version_tmp} CACHE INTERNAL "Matlab version (automatically determined)" FORCE)
1214

1215 1216 1217 1218
    # warning, just in case several versions found (should not happen)
    if((${list_of_all_versions_length} GREATER 1) AND MATLAB_FIND_DEBUG)
      message(WARNING "[MATLAB] Found several versions, taking the first one (versions found ${matlab_list_of_all_versions})")
    endif()
1219

1220 1221
    # return the updated value
    set(${matlab_final_version} ${Matlab_VERSION_STRING_INTERNAL} PARENT_SCOPE)
1222
  elseif(EXISTS "${matlab_root}/VersionInfo.xml")
1223 1224 1225 1226 1227
    # MCR
    # we cannot run anything in order to extract the version. We assume that the file
    # VersionInfo.xml exists under the MatlabRoot, we look for it and extract the version from there
    set(_matlab_version_tmp "unknown")
    file(STRINGS "${matlab_root}/VersionInfo.xml" versioninfo_string NEWLINE_CONSUME)
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239

    if(versioninfo_string)
      # parses "<version>9.2.0.538062</version>"
      string(REGEX MATCH "<version>(.*)</version>"
             version_reg_match
             ${versioninfo_string}
            )

      if(NOT "${version_reg_match}" STREQUAL "")
        if("${CMAKE_MATCH_1}" MATCHES "(([0-9])\\.([0-9]))[\\.0-9]*")
          set(_matlab_version_tmp "${CMAKE_MATCH_1}")
        endif()
1240 1241 1242 1243 1244 1245 1246
      endif()
    endif()
    set(${matlab_final_version} "${_matlab_version_tmp}" PARENT_SCOPE)
    set(Matlab_VERSION_STRING_INTERNAL
        "${_matlab_version_tmp}"
        CACHE INTERNAL "Matlab (MCR) version (automatically determined)"
        FORCE)
1247
  endif() # Matlab or MCR
1248

1249
endfunction()
1250 1251


1252 1253 1254 1255 1256
# Utility function for finding Matlab or MCR on Win32
function(_Matlab_find_instances_win32 matlab_roots)
  # On WIN32, we look for Matlab installation in the registry
  # if unsuccessful, we look for all known revision and filter the existing
  # ones.
1257

1258 1259
  # testing if we are able to extract the needed information from the registry
  set(_matlab_versions_from_registry)
1260

1261 1262 1263 1264 1265
  if(CMAKE_SIZEOF_VOID_P EQUAL 8)
    set(_matlab_win64 ON)
  else()
    set(_matlab_win64 OFF)
  endif()
1266

1267
  matlab_extract_all_installed_versions_from_registry(_matlab_win64 _matlab_versions_from_registry)
1268

1269 1270
  # the returned list is empty, doing the search on all known versions
  if(NOT _matlab_versions_from_registry)
1271
    if(MATLAB_FIND_DEBUG)
1272
      message(STATUS "[MATLAB] Search for Matlab from the registry unsuccessful, testing all supported versions")
1273
    endif()
1274
    extract_matlab_versions_from_registry_brute_force(_matlab_versions_from_registry)
1275 1276
  endif()

1277 1278 1279
  # filtering the results with the registry keys
  matlab_get_all_valid_matlab_roots_from_registry("${_matlab_versions_from_registry}" _matlab_possible_roots)
  set(${matlab_roots} ${_matlab_possible_roots} PARENT_SCOPE)
1280

1281
endfunction()
1282

1283 1284
# Utility function for finding Matlab or MCR on OSX
function(_Matlab_find_instances_osx matlab_roots)
1285

1286 1287 1288 1289 1290 1291 1292 1293 1294
  set(_matlab_possible_roots)
  # on mac, we look for the /Application paths
  # this corresponds to the behaviour on Windows. On Linux, we do not have
  # any other guess.
  matlab_get_supported_releases(_matlab_releases)
  if(MATLAB_FIND_DEBUG)
    message(STATUS "[MATLAB] Matlab supported versions ${_matlab_releases}. If more version should be supported "
                 "the variable MATLAB_ADDITIONAL_VERSIONS can be set according to the documentation")
  endif()
1295

1296 1297 1298 1299
  foreach(_matlab_current_release IN LISTS _matlab_releases)
    matlab_get_version_from_release_name("${_matlab_current_release}" _matlab_current_version)
    string(REPLACE "." "" _matlab_current_version_without_dot "${_matlab_current_version}")
    set(_matlab_base_path "/Applications/MATLAB_${_matlab_current_release}.app")
1300

1301 1302
    # Check Matlab, has precedence over MCR
    if(EXISTS ${_matlab_base_path})
1303
      if(MATLAB_FIND_DEBUG)
1304
        message(STATUS "[MATLAB] Found version ${_matlab_current_release} (${_matlab_current_version}) in ${_matlab_base_path}")
1305
      endif()
1306
      list(APPEND _matlab_possible_roots "MATLAB" ${_matlab_current_version} ${_matlab_base_path})
1307 1308
    endif()

1309 1310 1311 1312 1313
    # Checks MCR
    set(_mcr_path "/Applications/MATLAB/MATLAB_Runtime/v${_matlab_current_version_without_dot}")
    if(EXISTS "${_mcr_path}")
      if(MATLAB_FIND_DEBUG)
        message(STATUS "[MATLAB] Found MCR version ${_matlab_current_release} (${_matlab_current_version}) in ${_mcr_path}")
1314
      endif()
1315 1316
      list(APPEND _matlab_possible_roots "MCR" ${_matlab_current_version} ${_mcr_path})
    endif()
1317

1318 1319
  endforeach()
  set(${matlab_roots} ${_matlab_possible_roots} PARENT_SCOPE)
1320

1321
endfunction()
1322

1323 1324
# Utility function for finding Matlab or MCR from the PATH
function(_Matlab_find_instances_from_path matlab_roots)
1325

1326
  set(_matlab_possible_roots)
1327 1328

  # At this point, we have no other choice than trying to find it from PATH.
1329
  # If set by the user, this wont change
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
  find_program(
    _matlab_main_tmp
    NAMES matlab)

  if(_matlab_main_tmp)
    # we then populate the list of roots, with empty version
    if(MATLAB_FIND_DEBUG)
      message(STATUS "[MATLAB] matlab found from PATH: ${_matlab_main_tmp}")
    endif()

    # resolve symlinks
    get_filename_component(_matlab_current_location "${_matlab_main_tmp}" REALPATH)

    # get the directory (the command below has to be run twice)
    # this will be the matlab root
    get_filename_component(_matlab_current_location "${_matlab_current_location}" DIRECTORY)
    get_filename_component(_matlab_current_location "${_matlab_current_location}" DIRECTORY) # Matlab should be in bin

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
    # We found the Matlab program
    list(APPEND _matlab_possible_roots "MATLAB" "NOTFOUND" ${_matlab_current_location})

    # we remove this from the CACHE
    unset(_matlab_main_tmp CACHE)
  else()
    find_program(
      _matlab_mex_tmp
      NAMES mex)
    if(_matlab_mex_tmp)
      # we then populate the list of roots, with empty version
      if(MATLAB_FIND_DEBUG)
        message(STATUS "[MATLAB] mex compiler found from PATH: ${_matlab_mex_tmp}")
      endif()

      # resolve symlinks
      get_filename_component(_mex_current_location "${_matlab_mex_tmp}" REALPATH)

      # get the directory (the command below has to be run twice)
      # this will be the matlab root
      get_filename_component(_mex_current_location "${_mex_current_location}" DIRECTORY)
      get_filename_component(_mex_current_location "${_mex_current_location}" DIRECTORY) # Matlab Runtime mex compiler should be in bin

      # We found the Matlab program
      list(APPEND _matlab_possible_roots "MCR" "NOTFOUND" ${_mex_current_location})

      unset(_matlab_mex_tmp CACHE)
    else()
      if(MATLAB_FIND_DEBUG)
        message(STATUS "[MATLAB] mex compiler not found")
      endif()
    endif()
1380 1381 1382 1383


  endif()

1384 1385
  set(${matlab_roots} ${_matlab_possible_roots} PARENT_SCOPE)
endfunction()
1386 1387


1388 1389
# ###################################
# Exploring the possible Matlab_ROOTS
1390

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
# this variable will get all Matlab installations found in the current system.
set(_matlab_possible_roots)

if(Matlab_ROOT_DIR)
  # if the user specifies a possible root, we keep this one

  if(NOT EXISTS "${Matlab_ROOT_DIR}")
    # if Matlab_ROOT_DIR specified but erroneous
    if(MATLAB_FIND_DEBUG)
      message(WARNING "[MATLAB] the specified path for Matlab_ROOT_DIR does not exist (${Matlab_ROOT_DIR})")
    endif()
  else()
    # NOTFOUND indicates the code below to search for the version automatically
    if("${Matlab_VERSION_STRING_INTERNAL}" STREQUAL "")
      list(APPEND _matlab_possible_roots "UNKNOWN" "NOTFOUND" ${Matlab_ROOT_DIR}) # empty version, empty MCR/Matlab indication
    else()
      list(APPEND _matlab_possible_roots "UNKNOWN" ${Matlab_VERSION_STRING_INTERNAL} ${Matlab_ROOT_DIR}) # cached version
    endif()
  endif()
else()

  # if the user does not specify the possible installation root, we look for
  # one installation using the appropriate heuristics.
  # There is apparently no standard way on Linux.
1415
  if(CMAKE_HOST_WIN32)
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
    _Matlab_find_instances_win32(_matlab_possible_roots_win32)
    list(APPEND _matlab_possible_roots ${_matlab_possible_roots_win32})
  elseif(APPLE)
    _Matlab_find_instances_osx(_matlab_possible_roots_osx)
    list(APPEND _matlab_possible_roots ${_matlab_possible_roots_osx})
  endif()
endif()


list(LENGTH _matlab_possible_roots _numbers_of_matlab_roots)
if(_numbers_of_matlab_roots EQUAL 0)
  # if we have not found anything, we fall back on the PATH
  _Matlab_find_instances_from_path(_matlab_possible_roots)
endif()
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442


if(MATLAB_FIND_DEBUG)
  message(STATUS "[MATLAB] Matlab root folders are ${_matlab_possible_roots}")
endif()





# take the first possible Matlab root
list(LENGTH _matlab_possible_roots _numbers_of_matlab_roots)
set(Matlab_VERSION_STRING "NOTFOUND")
1443
set(Matlab_Or_MCR "UNKNOWN")
1444
if(_numbers_of_matlab_roots GREATER 0)
1445 1446 1447
  list(GET _matlab_possible_roots 0 Matlab_Or_MCR)
  list(GET _matlab_possible_roots 1 Matlab_VERSION_STRING)
  list(GET _matlab_possible_roots 2 Matlab_ROOT_DIR)
1448 1449

  # adding a warning in case of ambiguity
1450
  if(_numbers_of_matlab_roots GREATER 3 AND MATLAB_FIND_DEBUG)
1451 1452 1453 1454 1455 1456
    message(WARNING "[MATLAB] Found several distributions of Matlab. Setting the current version to ${Matlab_VERSION_STRING} (located ${Matlab_ROOT_DIR})."
                    " If this is not the desired behaviour, provide the -DMatlab_ROOT_DIR=... on the command line")
  endif()
endif()


1457 1458
# check if the root changed wrt. the previous defined one, if so
# clear all the cached variables for being able to reconfigure properly
1459 1460 1461 1462
if(DEFINED Matlab_ROOT_DIR_LAST_CACHED)

  if(NOT Matlab_ROOT_DIR_LAST_CACHED STREQUAL Matlab_ROOT_DIR)
    set(_Matlab_cached_vars
1463
        Matlab_VERSION_STRING
1464 1465 1466
        Matlab_INCLUDE_DIRS
        Matlab_MEX_LIBRARY
        Matlab_MEX_COMPILER
1467
        Matlab_MCC_COMPILER
1468 1469 1470
        Matlab_MAIN_PROGRAM
        Matlab_MX_LIBRARY
        Matlab_ENG_LIBRARY
1471
        Matlab_MAT_LIBRARY
1472 1473
        Matlab_ENGINE_LIBRARY
        Matlab_DATAARRAY_LIBRARY
1474
        Matlab_MEX_EXTENSION
1475
        Matlab_SIMULINK_INCLUDE_DIR
1476 1477 1478 1479 1480

        # internal
        Matlab_MEXEXTENSIONS_PROG
        Matlab_ROOT_DIR_LAST_CACHED
        #Matlab_PROG_VERSION_STRING_AUTO_DETECT
1481
        #Matlab_VERSION_STRING_INTERNAL
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
        )
    foreach(_var IN LISTS _Matlab_cached_vars)
      if(DEFINED ${_var})
        unset(${_var} CACHE)
      endif()
    endforeach()
  endif()
endif()

set(Matlab_ROOT_DIR_LAST_CACHED ${Matlab_ROOT_DIR} CACHE INTERNAL "last Matlab root dir location")
set(Matlab_ROOT_DIR ${Matlab_ROOT_DIR} CACHE PATH "Matlab installation root path" FORCE)

# Fix the version, in case this one is NOTFOUND
_Matlab_get_version_from_root(
  "${Matlab_ROOT_DIR}"
1497
  "${Matlab_Or_MCR}"
1498 1499
  ${Matlab_VERSION_STRING}
  Matlab_VERSION_STRING
Bill Hoffman's avatar
Bill Hoffman committed
1500 1501
)

1502 1503
if(MATLAB_FIND_DEBUG)
  message(STATUS "[MATLAB] Current version is ${Matlab_VERSION_STRING} located ${Matlab_ROOT_DIR}")
1504
endif()
Bill Hoffman's avatar
Bill Hoffman committed
1505

1506 1507 1508
if(NOT ${Matlab_VERSION_STRING} VERSION_LESS "9.4") # MATLAB 9.4 (R2018a) and newer have a new C++ API
  set(Matlab_HAS_CPP_API 1)
endif()
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546

if(Matlab_ROOT_DIR)
  file(TO_CMAKE_PATH ${Matlab_ROOT_DIR} Matlab_ROOT_DIR)
endif()

if(CMAKE_SIZEOF_VOID_P EQUAL 4)
  set(_matlab_64Build FALSE)
else()
  set(_matlab_64Build TRUE)
endif()

if(APPLE)
  set(_matlab_bin_prefix "mac") # i should be for intel
  set(_matlab_bin_suffix_32bits "i")
  set(_matlab_bin_suffix_64bits "i64")
elseif(UNIX)
  set(_matlab_bin_prefix "gln")
  set(_matlab_bin_suffix_32bits "x86")
  set(_matlab_bin_suffix_64bits "xa64")
else()
  set(_matlab_bin_prefix "win")
  set(_matlab_bin_suffix_32bits "32")
  set(_matlab_bin_suffix_64bits "64")
endif()



set(MATLAB_INCLUDE_DIR_TO_LOOK ${Matlab_ROOT_DIR}/extern/include)
if(_matlab_64Build)
  set(_matlab_current_suffix ${_matlab_bin_suffix_64bits})
else()
  set(_matlab_current_suffix ${_matlab_bin_suffix_32bits})
endif()

set(Matlab_BINARIES_DIR
    ${Matlab_ROOT_DIR}/bin/${_matlab_bin_prefix}${_matlab_current_suffix})
set(Matlab_EXTERN_LIBRARY_DIR
    ${Matlab_ROOT_DIR}/extern/lib/${_matlab_bin_prefix}${_matlab_current_suffix})
1547 1548
set(Matlab_EXTERN_BINARIES_DIR
    ${Matlab_ROOT_DIR}/extern/bin/${_matlab_bin_prefix}${_matlab_current_suffix})
1549 1550

if(WIN32)
1551 1552 1553 1554 1555
  if(MINGW)
    set(_matlab_lib_dir_for_search ${Matlab_EXTERN_LIBRARY_DIR}/mingw64)
  else()
    set(_matlab_lib_dir_for_search ${Matlab_EXTERN_LIBRARY_DIR}/microsoft)
  endif()
1556 1557
  set(_matlab_lib_prefix_for_search "lib")
else()
1558
  set(_matlab_lib_dir_for_search ${Matlab_BINARIES_DIR} ${Matlab_EXTERN_BINARIES_DIR})
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
  set(_matlab_lib_prefix_for_search "lib")
endif()

unset(_matlab_64Build)


if(NOT DEFINED Matlab_MEX_EXTENSION)
  set(_matlab_mex_extension "")
  matlab_get_mex_suffix("${Matlab_ROOT_DIR}" _matlab_mex_extension)

  # This variable goes to the cache.
  set(Matlab_MEX_EXTENSION ${_matlab_mex_extension} CACHE STRING "Extensions for the mex targets (automatically given by Matlab)")
  unset(_matlab_mex_extension)
endif()


if(MATLAB_FIND_DEBUG)
  message(STATUS "[MATLAB] [DEBUG]_matlab_lib_prefix_for_search = ${_matlab_lib_prefix_for_search} | _matlab_lib_dir_for_search = ${_matlab_lib_dir_for_search}")
endif()



# internal
# This small stub around find_library is to prevent any pollution of CMAKE_FIND_LIBRARY_PREFIXES in the global scope.
# This is the function to be used below instead of the find_library directives.
function(_Matlab_find_library _matlab_library_prefix)
  set(CMAKE_FIND_LIBRARY_PREFIXES ${CMAKE_FIND_LIBRARY_PREFIXES} ${_matlab_library_prefix})
  find_library(${ARGN})
endfunction()


set(_matlab_required_variables)


# the MEX library/header are required
find_path(
  Matlab_INCLUDE_DIRS
  mex.h
  PATHS ${MATLAB_INCLUDE_DIR_TO_LOOK}
  NO_DEFAULT_PATH
  )
list(APPEND _matlab_required_variables Matlab_INCLUDE_DIRS)

_Matlab_find_library(
  ${_matlab_lib_prefix_for_search}
  Matlab_MEX_LIBRARY
  mex
  PATHS ${_matlab_lib_dir_for_search}
  NO_DEFAULT_PATH
Bill Hoffman's avatar
Bill Hoffman committed
1608
)
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
list(APPEND _matlab_required_variables Matlab_MEX_LIBRARY)

# the MEX extension is required
list(APPEND _matlab_required_variables Matlab_MEX_EXTENSION)

# the matlab root is required
list(APPEND _matlab_required_variables Matlab_ROOT_DIR)

# component Mex Compiler
list(FIND Matlab_FIND_COMPONENTS MEX_COMPILER _matlab_find_mex_compiler)
if(_matlab_find_mex_compiler GREATER -1)
  find_program(
    Matlab_MEX_COMPILER
    "mex"
    PATHS ${Matlab_BINARIES_DIR}
    DOC "Matlab MEX compiler"
    NO_DEFAULT_PATH
  )
  if(Matlab_MEX_COMPILER)
    set(Matlab_MEX_COMPILER_FOUND TRUE)
  endif()
endif()
unset(_matlab_find_mex_compiler)

# component Matlab program
list(FIND Matlab_FIND_COMPONENTS MAIN_PROGRAM _matlab_find_matlab_program)
if(_matlab_find_matlab_program GREATER -1)
  find_program(
    Matlab_MAIN_PROGRAM
    matlab
    PATHS ${Matlab_ROOT_DIR} ${Matlab_ROOT_DIR}/bin
    DOC "Matlab main program"
    NO_DEFAULT_PATH
  )
  if(Matlab_MAIN_PROGRAM)
    set(Matlab_MAIN_PROGRAM_FOUND TRUE)
  endif()
endif()
unset(_matlab_find_matlab_program)

1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
# The MX library is required
_Matlab_find_library(
  ${_matlab_lib_prefix_for_search}
  Matlab_MX_LIBRARY
  mx
  PATHS ${_matlab_lib_dir_for_search}
  NO_DEFAULT_PATH
)
list(APPEND _matlab_required_variables Matlab_MX_LIBRARY)
if(Matlab_MX_LIBRARY)
  set(Matlab_MX_LIBRARY_FOUND TRUE)
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
endif()

# Component ENG library
list(FIND Matlab_FIND_COMPONENTS ENG_LIBRARY _matlab_find_eng)
if(_matlab_find_eng GREATER -1)
  _Matlab_find_library(
    ${_matlab_lib_prefix_for_search}
    Matlab_ENG_LIBRARY
    eng
    PATHS ${_matlab_lib_dir_for_search}
    NO_DEFAULT_PATH
  )
  if(Matlab_ENG_LIBRARY)
    set(Matlab_ENG_LIBRARY_FOUND TRUE)
  endif()
endif()
unset(_matlab_find_eng)

1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
# Component MAT library
list(FIND Matlab_FIND_COMPONENTS MAT_LIBRARY _matlab_find_mat)
if(_matlab_find_mat GREATER -1)
  _Matlab_find_library(
    ${_matlab_lib_prefix_for_search}
    Matlab_MAT_LIBRARY
    mat
    PATHS ${_matlab_lib_dir_for_search}
    NO_DEFAULT_PATH
  )
  if(Matlab_MAT_LIBRARY)
    set(Matlab_MAT_LIBRARY_FOUND TRUE)
  endif()
endif()
unset(_matlab_find_mat)
1693

1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
# Component Simulink
list(FIND Matlab_FIND_COMPONENTS SIMULINK _matlab_find_simulink)
if(_matlab_find_simulink GREATER -1)
  find_path(
    Matlab_SIMULINK_INCLUDE_DIR
    simstruc.h
    PATHS "${Matlab_ROOT_DIR}/simulink/include"
    NO_DEFAULT_PATH
    )
  if(Matlab_SIMULINK_INCLUDE_DIR)
    set(Matlab_SIMULINK_FOUND TRUE)
    list(APPEND Matlab_INCLUDE_DIRS "${Matlab_SIMULINK_INCLUDE_DIR}")
  endif()
endif()
unset(_matlab_find_simulink)
1709

1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
# component MCC Compiler
list(FIND Matlab_FIND_COMPONENTS MCC_COMPILER _matlab_find_mcc_compiler)
if(_matlab_find_mcc_compiler GREATER -1)
  find_program(
    Matlab_MCC_COMPILER
    "mcc"
    PATHS ${Matlab_BINARIES_DIR}
    DOC "Matlab MCC compiler"
    NO_DEFAULT_PATH
  )
  if(Matlab_MCC_COMPILER)
    set(Matlab_MCC_COMPILER_FOUND TRUE)
  endif()
endif()
unset(_matlab_find_mcc_compiler)

1726 1727 1728
if(Matlab_HAS_CPP_API)

  # The MatlabEngine library is required for R2018a+
1729 1730 1731 1732 1733 1734 1735 1736
  _Matlab_find_library(
    ${_matlab_lib_prefix_for_search}
    Matlab_ENGINE_LIBRARY
    MatlabEngine
    PATHS ${_matlab_lib_dir_for_search}
    DOC "MatlabEngine Library"
    NO_DEFAULT_PATH
  )
1737
  list(APPEND _matlab_required_variables Matlab_ENGINE_LIBRARY)
1738 1739 1740 1741
  if(Matlab_ENGINE_LIBRARY)
    set(Matlab_ENGINE_LIBRARY_FOUND TRUE)
  endif()

1742
  # The MatlabDataArray library is required for R2018a+
1743
  _Matlab_find_library(
1744
    ${_matlab_lib_prefix_for_search}
1745 1746 1747 1748 1749 1750
    Matlab_DATAARRAY_LIBRARY
    MatlabDataArray
    PATHS ${_matlab_lib_dir_for_search}
    DOC "MatlabDataArray Library"
    NO_DEFAULT_PATH
  )
1751
  list(APPEND _matlab_required_variables Matlab_DATAARRAY_LIBRARY)
1752 1753 1754
  if(Matlab_DATAARRAY_LIBRARY)
    set(Matlab_DATAARRAY_LIBRARY_FOUND TRUE)
  endif()
1755

1756 1757
endif()

1758 1759
unset(_matlab_lib_dir_for_search)

1760 1761 1762 1763
set(Matlab_LIBRARIES
  ${Matlab_MEX_LIBRARY} ${Matlab_MX_LIBRARY}
  ${Matlab_ENG_LIBRARY} ${Matlab_MAT_LIBRARY}
  ${Matlab_DATAARRAY_LIBRARY} ${Matlab_ENGINE_LIBRARY})
1764

1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
find_package_handle_standard_args(
  Matlab
  FOUND_VAR Matlab_FOUND
  REQUIRED_VARS ${_matlab_required_variables}
  VERSION_VAR Matlab_VERSION_STRING
  HANDLE_COMPONENTS)

unset(_matlab_required_variables)
unset(_matlab_bin_prefix)
unset(_matlab_bin_suffix_32bits)
unset(_matlab_bin_suffix_64bits)
unset(_matlab_current_suffix)
unset(_matlab_lib_dir_for_search)
unset(_matlab_lib_prefix_for_search)

if(Matlab_INCLUDE_DIRS AND Matlab_LIBRARIES)
  mark_as_advanced(
    Matlab_MEX_LIBRARY
    Matlab_MX_LIBRARY
    Matlab_ENG_LIBRARY
1785 1786
    Matlab_ENGINE_LIBRARY
    Matlab_DATAARRAY_LIBRARY
1787
    Matlab_MAT_LIBRARY
1788 1789 1790 1791 1792 1793 1794
    Matlab_INCLUDE_DIRS
    Matlab_FOUND
    Matlab_MAIN_PROGRAM
    Matlab_MEXEXTENSIONS_PROG
    Matlab_MEX_EXTENSION
  )
endif()