I’ve received a few emails recently regarding some packages I submitted on Matlab Central that include C code to be compiled into a MEX file. I’ve always developed MEX files with GCC on Linux and my understanding of C is rudimentary. I wasn’t too sure what was necessary to get them to compile on Windows with Visual Studio C++. Users reported that VC++ was giving tons of compilation errors.
Turns out it’s pretty straightforward. The C compiler in VS wants variables to be declared at the top of functions. It’s a very annoying limitation. The solution is change the extension of every .c file to .cpp to get it to compile with the C++ compiler, which has no such limitation. Obviously you’ll need to change #include statements accordingly. C++ is not a strict subset of C, but unless you’re doing something fancy it should compile as is. A nice side effect is that you no longer need to use the -std=c99 flag in GCC to get it to accept C++ // style comments.
I’ve updated mexme accordingly, so you can generate cross-platform MEX files with only a rudimentary understanding of C.
Some other gotchas include differing definitions of various numeric types across platforms (including 32-bit vs. 64-bit). The trick here is to type all non-doubles using the constant that the Mathworks define in mex.h:
UINT8_T UINT16_T UINT32_T UINT64_T INT8_T INT16_T INT32_T INT64_T REAL32_T //AKA single REAL64_T //AKA double
Assuming your code is plain jane C code that should be enough to get it to work.
If the mex file includes file IO or some other Linux-specific feature, you will need to do more work. You can try compiling with MinGW or Cygwin. There’s a package on SourceForge called gnumex that will get that running. Or you could use macros to select the appropriate OS-specific functions.
On a related note, you will want to get into the habit of using mwSize and mwIndex to refer to the sizes and index of a matrix, which will enable compatibility with -largeArrayDims.
2 responses to “Making cross-platform MEX files”
whaaaat you mean to say you declare variables willy-nilly? for shame. it’s the bad influence of learning to program in matlab first, I’d guess. It makes it that much harder to figure out what’s going on when you want to look through code months later and try to understand what variable is being declared as what.
(every programming book I’ve read tries to drill this into students)
You’re trolling, right? Ctrl+F or use a decent IDE (Eclipse or VS). If you can’t figure out what a variable is for months later, it’s because your code is 1) poorly engineered and 2) poorly documented.