I am using MATLAB under Ubuntu and want to compile a set of 2 c++ files with a header file, using mex. I show a basic example and the errors I am getting.
This code produces the text "hello" from the c++ function that begins from the mexFunction and is compiled in MATLAB using mex, (mex mexTryAlex.cpp):
#include <mex.h>
#include <iostream>
using namespace std;
void newfunc(){
cout<<"hello\n";
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
newfunc();
}
and it works normally. Now I try to use multiple files and a header file with mex. I create a header file try.h
:
#ifndef try_h
#define try_h
void newfunc();
#endif
and then the new function's file try.cpp
:
#include <mex.h>
#include <iostream>
#include <try.h>
using namespace std;
void newfunc(){
cout<<"hello\n";
}
These 3 files do not compile with mex
:
>> mex mexTryAlex.cpp try.cpp try.h
Warning: You are using gcc version "4.4.3-4ubuntu5)". The version
currently supported with MEX is "4.3.4".
For a list of currently supported compilers see:
http://www.mathworks.com/support/compilers/current_release/
try.cpp:4:17: error: try.h: No such file or directory
mex: compile of ' "try.cpp"' failed.
??? Error using ==> mex at 208
Unable to complete successfully.
Another attempt with using the -I
option:
>> mex -I mexTryAlex.cpp try.cpp try.h
Warning: You are using gcc version "4.4.3-4ubuntu5)". The version
currently supported with MEX is "4.3.4".
For a list of currently supported compilers see:
http://www.mathworks.com/support/compilers/current_release/
mexTryAlex.cpp:1:17: error: mex.h: No such file or directory
mexTryAlex.cpp:7: error: ‘mxArray’ has not been declared
mexTryAlex.cpp:7: error: ISO C++ forbids declaration of ‘mxArray’ with no type
mexTryAlex.cpp:7: error: expected ‘,’ or ‘...’ before ‘*’ token
mex: compile of ' "mexTryAlex.cpp"' failed.
??? Error using ==> mex at 208
Unable to complete successfully.
How can I get these files to compile?
using namespace std;
is not the best of ideas. Just usestd::cout
, or if you usecout
a lot and want to abbreviate it, useusing std::cout;
, but opening up the entire std namespace will give you headaches in the long run :) Just look around here on SO for pros/cons/discussions about this topic. – Rody Oldenhuis