MATLAB: How to link against external library files when compiling the MATLAB file with the MATLAB Compiler

MATLAB Compiler

I have a an MATLAB file that calls an external C/C++ function using the #%external pragma. I want to include additional external header files header1.h and header2.h located at C:\myproj\include\ and and link against library files lib1.lib and lib2.lib located at C:\myproj\lib\.

Best Answer

In order to link against external LIB-files, you will need to modify your compiler options file, which is created upon running MBUILD -SETUP. Perform the following steps, depending on which platform you are compiling on.
The options file can be found in the directory returned by the command PREFDIR and is called COMPOPTS.BAT on Windows and mbuildopts.sh on UNIX/Mac.
1a) On Windows, to add a new include directory, add it to the end of the INCLUDE flag, for example:
INCLUDE=%MSVCDir%\INCLUDE;%MSVCDir%\MFC\INCLUDE;%MSVCDir%\ATL\INCLUDE;%INCLUDE%;C:\myproj\include;
To add a new LIB-file, first add the directory containing the libraries to the LIB flag, for example:
set LIB=%MSVCDir%\LIB;%MSVCDir%\MFC\LIB;%LIB%
Then add the name of the library to the LINKFLAGS file:
set LINKFLAGS=kernel32.lib user32.lib gdi32.lib advapi32.lib oleaut32.lib ole32.lib /LIBPATH:"%LIBLOC%" /nologo
set LINKFLAGS=%LINKFLAGS% mclmcrrt.lib lib1.lib lib2.lib
1b) On UNIX/Mac systems, to add a new include directory, modify the CFLAGS for C applications or CXXFLAGS for C++ applications:
CFLAGS="$MFLAGS -ansi -D_GNU_SOURCE -pthread -fexceptions -I/usr/myinclude"
To add the library, modify the CLIBS flag (or CXXLIBS flag). To link libMyLib.lib, you would add
CLIBS="$RPATH $MLIBS -lm -lstdc++ -lmyLib"
Lastly add the directory containing the library to the LDFLAGS flag:
LDFLAGS='-pthread -L/mydir/mydirwithlibs'
2) Once you have made changes to your options file based on the platform you are on, save the changes to a filename of your choosing and compile your code specifying the new options file that you have created:
mcc -mv mymain.m myCfile.c -f <full_path_to_new_options_file>