2

This is part of my code:

double h;
double sigma;

/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
{
   double *nor;
   int n    =  mxGetScalar(prhs[0]);
   h        =  mxGetScalar(prhs[1]);
   nor      =  mxGetPr(prhs[2]);
   sigma    =  mxGetScalar(prhs[3]);

   double *x;    

   /* create the output vector */
    plhs[0] = mxCreateDoubleMatrix(1,n,mxREAL);

    /* get a pointer to the real data in the output matrix*/
    x = mxGetPr(plhs[0]);    

    /* call the computational routine */
    createTRR(x,n,nor);
}

If I try to compile it in matlab with mex myfilename.c I get the following errors:

  1. error C2143: syntax error : missing ';' before 'type' (in this line: double *x; )
  2. error C2065: 'x' : undeclared identifier (in this line x = mxGetPr(plhs[0]);) and
  3. error C2065: 'x' : undeclared identifier (in this line createTRR(x,n,nor);)

I dont see whats wrong, and I also dont understand why no error is thrown for *nor but only for *x. I wrote the code with Matlab2012 on ubuntu and it worked. Now I am currently using Matlab 2013b on Win7 with Microsoft Software Development Kit (SDK) 7.1 as C++ compiler.

Shai
  • 111,146
  • 38
  • 238
  • 371
Adam
  • 25,960
  • 22
  • 158
  • 247

2 Answers2

1

your code is C++ and not strictly c: you declare variable x after the begining of the code of the function. As you may recall in C you must declare all local variables before the code of the function.

Cahnge your file extension to cpp and re-mex it.

Shai
  • 111,146
  • 38
  • 238
  • 371
  • 1
    C has declarations mixed with statements since C99. Probably he is just missing the correct compiler flags. – Jens Gustedt Mar 06 '14 at 22:03
  • @JensGustedt That's right but `mex` uses ANSI (C89/C90) by default, which doesn't support it. I assume you already saw it, but the command line fix is in my answer. – chappjc Mar 06 '14 at 22:24
0

When compiled as ANSI C code, you can't declare variables after code. You can do as Shai suggests and rename to .cpp, or you can leave the file name alone and enable the C99 standard, which allows declarations in the code:

mex -v -largeArrayDims CFLAGS="\$CFLAGS -std=C99" file.c 

This also enables the use of C++ style comments in the file (i.e. // C++-style comment).

See also Why was mixing declarations and code forbidden up until C99?.

Community
  • 1
  • 1
chappjc
  • 30,359
  • 6
  • 75
  • 132