How to create a Mex project using Linux Eclipse

This method for creating Matlab Mex executable file has been tested using Matlab R2010b & Eclipse 3.7.1 & 64 bit Fedora 16 Linux system.

0. Compile Mex in Matlab command prompt

For your information, C/C++ Mex file can be compiled in Matlab command prompt using ‘mex’, for instance,

mex –g –v GNUMex.c

The OpenMP support can be turned on by adding compiling and linker flag ‘-fopenmp’, such as

mex –g -v GNUMexOpenMP.c CFLAGS="\$CFLAGS -fopenmp" LDFLAGS="\$LDFLAGS -fopenmp"

or

mex –g -v GNUMexOpenMP.cpp CXXFLAGS="\$CXXFLAGS -fopenmp" LDCXXFLAGS="\$LDCXXFLAGS -fopenmp"

 1. Creation of an empty project

  • Create a simple C or C++ project under Eclipse (File / New/ C Project), name it as you wish

  • Choose Empty Project under Shared Library, follow project wizard until an empty C or C++ project is created

2. Configuration of Compiler

Now we need to define some important properties of the project to ensure that the output file is fully compatible with Matlab. Open project properties (Right click on the project name / Properties). Start with the “ C/C++ Build” tab

  • Under “Settings/Tool Settings/Cross GCC Compiler/Symbols,” add ‘MATLAB_MEX_FILE’ as a defined symbols

  • Under “Settings/Tool Settings/Cross GCC Compiler/Includes” add Matlab include folder which is usually /home/Username/MATLAB/R2010b/extern/include

  • Under “Settings/Tool Settings/Cross GCC Linker/Libraries” add Matlab library folder which is usually /home/Username/MATLAB/R2010b/bin/glnxa64 for 64bit Linux system, this path may vary according to your system, however, do not use /home/Username/MATLAB/R2010b/extern/lib

  • Under “Settings/Tool Settings/Cross GCC Linker/Libraries” also add Matlab library file libmat.so, libmx.so and libmex.so into the Libraries section since many default Mex functions are linked to these libraries. Note here mat, mx, and mex are added, this will be fine otherwise, a missing function error will appear.

  • We also need to configure the output file, since the default output file extension is not compatible with Matlab. Under “Settings/Build Artifact” change Artifact extension as ‘mexa64’ for 64bit Linux or ‘mexa32’ for 32bit, Output prefix can be left as blank.

3. Configuration for OpenMP

If OpenMP is used in the source code, this step is necessary, otherwise ignore this part.

  • Open features for OpenMP by adding ‘-fopenmp’ under ‘Command’ boxes for both ‘Cross GCC Compiler’ and ‘Cross GCC Linker’ (not shown here).

  • Also, check the ‘-fPIC’ flag for successful compiling, this option is under ‘Cross GCC Compiler/Miscellaneous’.

4. mexFunction

Add a main C/C++ file that contains the body of “mexFunction” with the following code snippet ( do not forget to include the “mex.h” header file to give access to the prototype of the mexFunction). Of course, any needed header files have to be put at the front of the source file, such as

#include "mex.h"
#include <stdio.h>
#include <omp.h>
void mexFunction(int nlhs,mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
   int count;
   int th_id;
   #pragma omp parallel for private(count, th_id) num_threads(2)
   for( count = 0; count < 60; count++ )
   {
      th_id = omp_get_thread_num();
      printf("Hello World from thread %d, %d\n", th_id, count);
   }
   printf( "Finished\n" );
}

5. Building

Now, if you build the project (Right click / “Build”), you will get a mexw32 file (or mexw64) which can be executed in Matlab.

6. Conclusion

After all the steps, you will be able to compile your Mex file in Eclipse, as I did. Some online tutorials require adding a module-definition file (.def) and ‘mexversion.rc’. However, Matlab removed ‘mexversion.rc’ in recent releases (?). I have tested compiling mex file under Visual Studio 2008 without this file, and it turned out just fine. Unsurprisingly it also turned out fine for compiling Mex without this file under linux.  I also tried to add .def file, as mentioned online, But I always got the error “unrecognized option –Wl, --output-def = XXX”. After trying solutions for hours, I finally decided to drop this file, and it worked just fine. In conclusion, I would recommend compiling using the default Matlab Mex script for a simple Mex project. So take your own risk to compile this way and enjoy the power of Mex.

Also, check "How to create a Mex project using Visual Studio 2008" for compiling Mex in Windows.

How to create a Mex project using Visual Studio 2008

This method for creating Matlab Mex executable file has been tested using Matlab R2011b & Microsoft Visual Studio 2008 & 64-bit Windows 7 OS system.

1. Creation of an empty project

  • Create a simple project under VC++ (File / New Project), name it as you wish

  • On the left-hand side, click on “Application Settings” (or, equivalently, click on the “Next” button) and make sure you select “DLL” and check “Empty project.”

  • Creation of the definition file

To run your code, Matlab needs to know where the “entry point” is. In any M-files, the execution starts at the first line of the first function found in the file. Other functions may exist in the file, but they are executed only when called. In the case of MEX files, Matlab will always try to run a function called “mexFunction”. Therefore we need to tell the compiler that this function needs to be accessible from outside. You can do as follows :

* Create a new empty file with the extension “.def”. In this case, I have added the file “keepPos.def”.

(An easy way to do this is to create a simple header file and rename it “Right click on the project name / Add / New Item / Header File and update the name")

* Move the file to the root of the project.

This file is called a definition file. As explained before, this file is used by the compiler/linker to know which functions are accessible from outside.

Here is the syntax to follow:

LIBRARY KEEPPOS # here could be your project name 
EXPORTS mexFunction

2. Configuration of Compiler

We need to define some important properties of the project to ensure that the output file is fully compatible with Matlab. Open project properties (Right-click on the project name / Properties). Start with the “Configuration Properties / C/C++” tab.

  • Under “General / Additional Include Directories ”add a Matlab external include directory : (I am also using Intel IPP, so Intel IPP include directory is also added here)

  • Then add the following string “MATLAB_MEX_FILE” to the list of Preprocessor definitions.

  • Ensure that under “Advanded”, the convention “_cdecl” is chosen.

3. Configuration of Linker

Now look at the “Configuration Properties / Linker” properties

  • Under “General”, define the name of the “Output file”: remember the extension must be .mexw32 (or .mexw64 under 64bit Windows), and the file name will be the name of the function in Matlab.

  • In the same screen, we now add the additional Matlab library directories (Also, I am using Intel IPP, so the Intel IPP lib directory is added here)

As we use a Microsoft Visual C++ compiler in this example, we select versions compatible with Windows.

  • We now add the libraries in “Additional Dependencies” ( “libmat.lib”, “libmex.lib” and “libmx.lib” for Matlab), corresponding libraries for IPP and other libraries used in the source code.
  • Last we define the “Definition file” for the library

4. Adding Matlab resource file (not necessary)

Add the MEX Resource file: “Right click / Add / Existing Item”, add the file “mexversion.rc” from the directory “{$Matlab}/extern/include”.

I spent lots of time trying to find this resource file in my system. However, I ain't been able to get it. Matlab decided not to keep this file any longer for their new Matlab release (at least for R2011b, under which I am testing). This file tells the system information about the Matlab version and Mex script version (you can tell from the file name:). After struggling hours on the internet trying to find a solution, there seems to be no easy way to explicitly avoid this (maybe you can find one:). Finally, I found a Chinese forum where people tested without this file, which worked. So I decided to be blind to this file. It proves that they were right. This file is not necessary for compiling and linking. Matlab may have made a smart way to implicitly avoid this file, or this information of this file is not needed in my code?!. For your information, I have added a sample of this file I found on the internet here:

/////////////////////////////////////////////////////////////////////////////
//  Copyright 1997-2008 The MathWorks, Inc.
//
//  Mex versioning resource file
//  This should be compiled with the ARRAY_ACCESS_INLINING
//  define if it applies.
//
//  DO NOT EDIT - this is for MATLAB use only
/////////////////////////////////////////////////////////////////////////////

//  Define strings,
//  ML_VERSION is the version of Matlab that the Mex file is built against.
//  INLINING determines in inlining was switched on or not.
#define ML_VERSION       100
#define INLINING     101
/////////////////////////////////////////////////////////////////////////////
//
// String Table
//
STRINGTABLE
BEGIN
ML_VERSION,          "MATLAB R14 native"
#ifdef ARRAY_ACCESS_INLINING
INLINING,               "inlined"
#else
INLINING,               "not inlined"
#endif
END

5. mexFunction

Add a main C/C++ file that contains the body of “mexFunction” with the following code snippet ( do not forget to include the “Mex.h” header file to give the prototype of the mexFunction). Of course, header files have to be put at the front of the source file, such as

#include <math.h>
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <Mex.h> // Mex header
#include "matrix.h"
#include <ipp.h> // Intel IPP header
#ifdef MULTITHREADING_OMP
#include <omp.h> // OpenMP header
#endif

6. Turn on OpenMP

If your code uses the multi-threading functions and directives from OpenMP (supported by Visual Studio), you must turn on options for the compiler to recognize your implementation. Go to Project Properties-> C/C++ -> Language, change OpenMP Support to "Yes".

7. Solution Platform

If you are compiling the Mex file under a 64bit Windows system, one more step has to be taken. Go to the Project Property-> Configuration Manager. Change the Active solution platform to x64 instead of Win32.

Click <New> and choose x64 from the drop menu.

8. Building

Now, if you build the project (Right click / “Build”), you will get a mexw32 file (or mexw64) which can be executed in Matlab.

Note that if a MEX function is running, Matlab keeps a handle on the file where it is defined. Therefore if you want to rebuild your file you need to free the handle by using a simple “clear keepPos” command in Matlab prompt.

9. Conclusion

After all the steps, you should be able to compile your Mex file in Visual Studio, as I did. I tried this approach to compile source Mex C code called by Matlab GUI application, and it worked just fine. Also, I managed to compile the same code using Matlab default Mex script, and I noticed that you might need to change a couple of lines to satisfy different compiling. Also, compatibility conflicts may arise when you compile Mex files using different tools. I recommend compiling using the default Matlab Mex script to avoid problems for small projects. That being said, take your own risk to compile this way and enjoy the power of Mex.

Also, check "How to create a Mex project using Linux Eclipse" for compiling Mex in Linux.