Using GCC (MinGW) as MATLAB's MEX compiler

Menyh picture Menyh · Dec 18, 2011 · Viewed 57.4k times · Source

I've been given a project to run on MATLAB R2011a. As there are several .c files in there - I need to set up GCC as the MEX compiler for that project. However, I cannot seem to find any explanation as to how to set it up. I've tried a script program called gnumex - but it failed (probably set up for an older version of MATLAB).

Any idea how to set it up?

Answer

Bogdan picture Bogdan · Sep 16, 2012

Why not adjust the mexopts.bat file in your directory? That way you can use the "mex" command transparently to compile anything, as usual in MATLAB, the same as if it was configured by MATLAB using mex -setup. I'm surprised nobody did this before.

The file below is for x64 version of Matlab and Mingw. I'm using the TDM Mingw64 distribution, which I installed in p:\mingw64-tdm. I have Matlab installed in p:\matlab\R2012a -- edit those accordingly.

This is the mexopts.bat file I'm using, copy paste this in %USERPROFILE%\AppData\Roaming\MathWorks\MATLAB\R2012a\mexopts.bat:

@echo off

set MINGWPATH=p:\mingw64-tdm
set PATH=%MINGWPATH%\bin;%PATH%

set COMPILER=gcc
set COMPFLAGS=-c -m64 -I"%MATLAB%\extern\include" -DMATLAB_MEX_FILE -Wall -std=c99
set OPTIMFLAGS=-O3 -DNDEBUG
set DEBUGFLAGS=-g
set NAME_OBJECT=-o

set LINKER=gcc
set LINKFLAGS=-shared -L"%MATLAB%\bin\win64" -L"%MATLAB%\extern\lib\win64\microsoft" -lmex -lmx -leng -lmat -lmwlapack -lmwblas
set NAME_OUTPUT=-o "%OUTDIR%%MEX_NAME%%MEX_EXT%"

Then you can just try doing this in Matlab:

mex -v p:\matlab\R2012a\extern\examples\mex\yprime.c
which yprime

Should yield b:\code\m\yprime.mexw64 (or whatever the current folder is). Then if you do:

yprime(1,1:4)

You should see:

ans =
    2.0000    8.9685    4.0000   -1.0947

Which means you're in business. Good luck!

EDIT Oct 2014: I now use an improved mexopts.bat file than the above with a different MinGW64 (yields slightly faster binary code than TDM's). See my homepage for details and downloads.