mex compile error caused by different position of mexPrintf()

2 views (last 30 days)
I have got this code from website, saved it as hello.c and set up mex using MSVC 2010 compiler. It gives me compile errors. Such as illegal use of mxArray and undefined variables error.
#include <matrix.h>
#include <math.h>
#include <mex.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
mexPrintf("hello, world!\n");
//declare variables
mxArray *a_in_m;
mxArray *b_in_m;
mxArray *c_out_m;
mxArray *d_out_m;
const mwSize *dims;
double *a, *b, *c, *d;
int dimx, dimy, numdims;
//associate inputs
a_in_m = mxDuplicateArray(prhs[0]);
b_in_m = mxDuplicateArray(prhs[1]);
//figure out dimensions
dims = mxGetDimensions(prhs[0]);
numdims = mxGetNumberOfDimensions(prhs[0]);
dimy = (int)dims[0]; dimx = (int)dims[1];
//associate outputs
c_out_m = plhs[0] = mxCreateDoubleMatrix(dimy, dimx, mxREAL);
d_out_m = plhs[1] = mxCreateDoubleMatrix(dimy, dimx, mxREAL);
}
However, when I put the mexPrintf sentence in after the declaration part. The errors are gone.
#include <matrix.h>
#include <math.h>
#include <mex.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
//declare variables
mxArray *a_in_m;
mxArray *b_in_m;
mxArray *c_out_m;
mxArray *d_out_m;
const mwSize *dims;
double *a, *b, *c, *d;
int dimx, dimy, numdims;
mexPrintf("hello, world!\n");
//associate inputs
a_in_m = mxDuplicateArray(prhs[0]);
b_in_m = mxDuplicateArray(prhs[1]);
//figure out dimensions
dims = mxGetDimensions(prhs[0]);
numdims = mxGetNumberOfDimensions(prhs[0]);
dimy = (int)dims[0]; dimx = (int)dims[1];
//associate outputs
c_out_m = plhs[0] = mxCreateDoubleMatrix(dimy, dimx, mxREAL);
d_out_m = plhs[1] = mxCreateDoubleMatrix(dimy, dimx, mxREAL);
}
Could anyone explain why this happens? Thanks!

Accepted Answer

Ryan Livingston
Ryan Livingston on 11 Mar 2013
Edited: Ryan Livingston on 11 Mar 2013
In C (C89 and older I believe) variables must be declared at the beginning of a scope before any other statements are made in the code. So having that function call before declaring variables makes the compiler unhappy.
You could rename the file to .cpp and that should pacify it or just leave the declarations first.

More Answers (0)

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!