FindMATLAB: matlab_add_mex command is broken since CMake v3.14 with MSVC 15.4
It seems that the matlab_add_mex
command is broken (at least for MSVC 15.4 using Windows 7) since version 3.14.0 of CMake.
Short, Self Contained, Correct Example (SSCCE)
CMakeLists.txt
:
cmake_minimum_required(VERSION 3.14.5)
include(FindMatlab)
project(cpp-example-matlab_mex LANGUAGES CXX)
matlab_get_version_from_release_name("R2018b" Matlab_VERSION)
find_package(Matlab ${Matlab_VERSION})
matlab_add_mex(
NAME example_mex
SRC "${CMAKE_CURRENT_SOURCE_DIR}/mex_function.cpp"
R2018a
)
mex_function.cpp
:
// MATLAB
#include <mex.h>
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, mxArray const* prhs[]) {
// NOOP
}
build.cmd
:
@echo off
cls
cmake ^
-G "Visual Studio 15 2017 Win64" ^
-T v141 ^
-S . ^
-B _build ^
-DCMAKE_CXX_COMPILER:FILEPATH=cl ^
-DCMAKE_SYSTEM_VERSION:STRING=10.0.16299.0 ^
-DMatlab_ROOT_DIR:PATH="C:/Program Files/Matlab/R2018b" ^
-DMATLAB_FIND_DEBUG:BOOL=OFF
cmake --build _build --config Debug
Running build.cmd
gives the following linker errors ("unresolved symbol"):
LINK : error LNK2001: Nicht aufgelöstes externes Symbol "mexCreateMexFunction". [C:\dev\_build\example_mex.vcxproj]
LINK : error LNK2001: Nicht aufgelöstes externes Symbol "mexDestroyMexFunction". [C:\dev\_build\example_mex.vcxproj]
LINK : error LNK2001: Nicht aufgelöstes externes Symbol "mexFunctionAdapter". [C:\dev\_build\example_mex.vcxproj]
LINK : error LNK2001: Nicht aufgelästes externes Symbol "mexfilerequiredapiversion". [C:\dev\_build\example_mex.vcxproj]
C:/dev/_build/Debug/example_mex.lib : fatal error LNK1120: 4 nicht aufgelöste Externe [C:\dev\_build\example_mex.vcxproj]
Workaround
Commenting out lines 1028 and 1033 of FindMatlab.cmake
as follows:
set(_link_flags "${_link_flags} /EXPORT:mexFunction")
if(NOT ${Matlab_VERSION_STRING} VERSION_LESS "9.1") # For 9.1 (R2016b) and newer, export version
# TODO(2019-06-14 by wolters): Linker error with Microsoft Visual Studio 2017.
#set(_link_flags "${_link_flags} /EXPORT:mexfilerequiredapiversion")
endif()
if(Matlab_HAS_CPP_API)
# TODO(2019-06-14 by wolters): Linker error with Microsoft Visual Studio 2017.
#set(_link_flags "${_link_flags} /EXPORT:mexCreateMexFunction /EXPORT:mexDestroyMexFunction /EXPORT:mexFunctionAdapter")
#TODO: Is this necessary?
endif()
Questions
- Why are these three functions exported at all?
- Is there a workaround that does not require to hack
FindMatlab.cmake
?
Edited by Brad King