Setting RPATH for Matlab mex compilation

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

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

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

Set LD_LIBRARY_PATH:
Use the setenv and getenv command in Matlab.

Set RPATH:
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
Comments:
  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 mexopts.sh script:
  A. Locate the mexopts.sh 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:
RPATH=”-Wl,-rpath-link,/home/xxx/mylib:$TMW_ROOT/bin/$Arch,-rpath=/home/xxx/mylib:$TMW_ROOT/bin/$Arch”.

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 mexopts.sh
  RPATH=”-Wl,-rpath-link,$TMW_ROOT/bin/$Arch,-rpath=’\\\$ORIGIN’:$TMW_ROOT/bin/$Arch”.
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

Advertisements

One comment

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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