Mex using MSVC fails to compile a C function previously successfully compiled with Linux GCC
System information
----------------------------------------------------------------------------------------------------
MATLAB Version: 8.5.0.197613 (R2015a)
MATLAB License Number: 833957
Operating System: Microsoft Windows 8.1 Pro Version 6.3 (Build 9600)
Java Version: Java 1.7.0_60-b19 with Oracle Corporation Java HotSpot(TM) 64-Bit Server VM mixed mode
----------------------------------------------------------------------------------------------------
Microsoft Visual Studio 2013
The error message is as follows:
>> mex MyFunc.c
Building with 'Microsoft Visual C++ 2013 Professional (C)'.
Error using mex
MyFunc.c
C:\Users\Qingju\Desktop\Test\MyFunc.c(38) : error C2143: syntax error : missing ';' before 'const'
C:\Users\Qingju\Desktop\Test\MyFunc.c(39) : error C2065: 'dims' : undeclared identifier
C:\Users\Qingju\Desktop\Test\MyFunc.c(39) : error C2109: subscript requires array or pointer type
C:\Users\Qingju\Desktop\Test\MyFunc.c(49) : error C2065: 'dims' : undeclared identifier
C:\Users\Qingju\Desktop\Test\MyFunc.c(49) : warning C4047: 'function' : 'const int *' differs in levels of
indirection from 'int'
C:\Users\Qingju\Desktop\Test\MyFunc.c(49) : warning C4024: 'mxCreateNumericArray_700' : different types for
formal and actual parameter 2
>> mex -setup
MEX configured to use 'Microsoft Visual C++ 2013 Professional (C)' for C language compilation.
Warning: The MATLAB C and Fortran API has changed to support MATLAB
variables with more than 2^32-1 elements. In the near future
you will be required to update your code to utilize the
new API. You can find more information about this at:
http://www.mathworks.com/help/matlab/matlab_external/upgrading-mex-files-to-use-64-bit-api.html.
To choose a different language, select one from the following:
mex -setup C++
mex -setup FORTRAN
This is because
If you configure your compiler to compile C code conform to the C89-standards, the variables must be declared before the code. The declaration inside the code is a C++ or C99 style
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int *faces, n; double *img, threshold; int size; const mwSize *dim; ... /* Checks. */ dim = mxGetDimensions(prhs[0]);
MSVC does accept the C++ and C99-style comments started by // in opposite to GCC, which is configured to the C89-style by Matlab. It seems like MSVC is stricter as GCC for the rule "declarations before statements".
To address this problem, simple rename MyFunc.c to MyFunc.cpp.