Setting RPATH for Matlab mex compilation

Platform: Linux
A mex file seems to be compiled successfully, but at run-time Matlab issues error because dependent libraries cannot be found.

At run-time, Matlab failed locate the correct dependent library for the mex file.

(1) Set environmental variable LD_LIBRARY_PATH in Matlab, OR
(2) Set RPATH in the mex file during the linking procedure.

Use the setenv and getenv command in Matlab.

You can insert the following option in the command line invokation of mex:
  LDFLAGS=’$LDFLAGS -Wl,-rpath=Your_RPATH’
For example:
  mex LDFLAGS=’$LDFLAGS -Wl,-rpath=Your_RPATH’ mycode.cxx
  LDFLAGS=’$LDFLAGS …’ appends “…” to LDFLAGS after mex has setup its compilation variables, so Matlab’s setup is automatically get involved.
  -Wl,aaa,bbb (comma separated, not blanks) will be passed to ld as options aaa bbb (blank separated).

If you want to permanently add this to your mex compilation, you can modify the script:
  A. Locate the script, and locate the lines setting “RPATH”.
  B. Insert “-rpath-line,Your_RPATH,-rpath=Your_RPATH” to the value of RPATH. For example,
The original value might be: RPATH=”-Wl,-rpath-link,$TMW_ROOT/bin/$Arch”.
You can replace with:

If you want to use relative paths, then use ‘\\\$ORIGIN’ to stand for the path of the mex file. For example:
in the command line
  mex LDFLAGS=’$LDFLAGS -Wl,-rpath=\\\$ORIGIN’ mycode.cxx
Or in the
In the compiled mex, you will find “$ORIGIN” is listed in the rpath of the mex file.
Comment: “\” is the escape character. After twice variable expansion, \\\$ORIGIN will become ‘$ORIGIN’

Inspect the RPATH of the mex file with “chrpath” command, with the “-l” option. For example,
chrpath -l myfunc.mex


One comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s