Adam
Adam

Reputation: 28968

Strange error on c++ matlab code

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.

Upvotes: 2

Views: 235

Answers (2)

chappjc
chappjc

Reputation: 30579

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?.

Upvotes: 0

Shai
Shai

Reputation: 114786

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.

Upvotes: 1

Related Questions