Compile MEX files that use external libraries

Often, when I'm writing a MEX file I need to use external libraries like Eigen or Boost to handle some common numerical methods.

Usually, this can be easily accomplished by both including the relevant source files and referencing them properly.

For example, suppose I need to use the error function (erf) and inverse error function (erf_inv) routines in Boost.

In the header, I would add the statement:

#include <boost/math/special_functions/erf.hpp>

Then in the code itself, I would write out the full path to the function in question

double myinvnormcdf( double p ) {
  return SQRT2 * boost::math::erf_inv( 2*p -1 );

Common Errors

Often, I've found that the code with compile successfully via MEX, but when I try to run it, I get an error:

Invalid MEX-file version  (blah blah blah)...
<path/to/matlab/on/my/system/> version `GLIBCXX_3.4.11' not found

Essentially, the problem is that Matlab loads in its own default C++ libraries, and these do not play nice with what is required by Boost. Particularly, Boost wants to use "", but Matlab's own libraries don't have this available.

To solve this problem I found this thread at matlab central to be quite valuable. Particularly the last comments by a user named Yogesh.

To correct this, you can start Matlab with a pointer to which libraries to use instead.  Usually, I start up Matlab at a terminal

$ /local/bin/matlab

Your system might have a slightly different path (e.g. /usr/bin/ or /opt/bin/). To find the right path, just type which matlab. You may not even need the path, if matlab's executable is in your path by default.

Instead, I just use this one-liner at the terminal

$ LD_PRELOAD=/usr/lib/ /local/bin/matlab

This command just makes sure the required library is available.

Note that you might need to replace "/usr/lib/" with the right path on your system.  You can usually get this by typing locate

That's it!  Hope this helps.  Note that other solutions involving renaming Matlab's are possible, but these didn't work for me since I don't have root access to the department-wide install.