How do I compile with shared libraries for my MEX files on Linux?

I'm trying to compile a CPP script, "foo.cpp", that relies on a shared library, "libfoolibrary.so", into a MEX file on Linux. However, even though it compiles successfully, it fails at runtime, giving me the following error message:
>> mex -DLIN -DUNIX -DNDEBUG -D_USRDLL -O foo.cpp -output foo_mex -lfoolibrary -L./
Building LIN64 MEX function...
Building with 'g++'.
MEX completed successfully.
MEX function compilation completed successfully
>> foo_mex
Running the MEX function... Invalid MEX-file '/home/MATLAB/foo_mex.mexa64': libfoolibrary.so: cannot open shared object file: No such file or directory
This doesn't happen when I try to do this on Windows. Am I doing something wrong?

 Accepted Answer

The issue is that even though you have told the "g++" command that it is looking for a shared library called "libfoolibrary.so" in the current directory when compiling, the GNU linker itself doesn't know where to look for dependencies at runtime.
 
Passing the options "-Wl,-rpath,\$ORIGIN" to the "LDFLAGS" flag would add the current directory ("$ORIGIN") to the dynamic library search path. So, at runtime, the dynamic loader would look for dependencies in the current directory (or any directory specified with "-rpath"). On computers running Windows, the current directory is added by default, so this would not be necessary.
Dependencies are searched for by the GNU linker in the following order:
    1. Directories in "rpath"
    2. Directories in "LD_LIBRARY_PATH"
    3. System directories 
For more information about the GNU linker and its many options, you can look at its "man" page:
In your case, the following command should allow your MEX file to compile and run successfully, assuming that your SO file is in the same directory as your CPP file:
mex -DLIN64 -DUNIX -DNDEBUG -D_USRDLL -O xfft_v9_1_bitacc_mex.cpp ...
-output xfft_v9_1_bitacc_mex -lIp_xfft_v9_1_bitacc_cmodel -L./ 'LDFLAGS=$LDFLAGS -Wl,-rpath,\$ORIGIN'

More Answers (0)

Categories

Find more on MATLAB Compiler in Help Center and File Exchange

Products

Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!