This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.


Build MEX function from C/C++ or Fortran source code


mex filenames
mex option1 ... optionN filenames
mex -setup lang
mex -setup -client engine [lang]




The mex command builds MEX functions and engine applications written with the MATLAB Data API, the C Matrix API, and the Fortran Matrix API.

mex filenames compiles and links one or more C, C++, or Fortran source files into a binary MEX file, callable from MATLAB®. filenames specify the source files. Also builds executable files for standalone MATLAB engine and MAT-file applications.

MATLAB automatically selects a compiler, if installed, based on the language of the filenames arguments.


mex option1 ... optionN filenames builds with the specified build options. The option1 ... optionN arguments supplement or override the default mex build configuration.

mex -setup lang selects a compiler for the given lang. Use this option to change the default compiler for the given language.

mex -setup -client engine [lang] selects a compiler for building engine applications. Use this option when you want to change the default compiler. Use the lang argument for choosing Fortran or C++ compilers.


collapse all

Build a single C program yprime.c into a MEX file.

Create a writable folder on your path c:\work and set it as the current folder.

[s,msg,msgid] = mkdir('c:\work');
if (isempty(msgid))
cd c:\work

Copy the source code example from the matlabroot/extern/examples folder.


Build the MEX file. The output displays information specific to your compiler.

mex yprime.c
Building with 'MinGW64 Compiler  C '.
MEX completed successfully.


ans =

    2.0000    8.9685    4.0000   -1.0947

To display the compile and link commands and other information useful for troubleshooting, use verbose mode.

mex -v -compatibleArrayDims yprime.c

The output displays information specific to your platform and compiler.

Build the yprime.c MEX file by appending the value -Wall to the existing compiler flag. Because the value includes a space character, you must delineate the string; the character you use depends on the platform.

At the MATLAB prompt, use MATLAB single quotes (').

mex -v COMPFLAGS='$COMPFLAGS -Wall' yprime.c

For the MinGW-w64 compiler, which is based on gcc/g++, use the Linux® compiler flags.

mex -v CXXFLAGS='$CXXFLAGS -Wall' yprime.c

At the Windows® Command Prompt, use double quotes (").

mex -v COMPFLAGS="$COMPFLAGS -Wall" yprime.c

At the shell command line on Mac and Linux, use single quotes (').

mex -v CFLAGS='$CFLAGS -Wall' yprime.c

The MEX file example fulltosparse consists of two Fortran source files, loadsparse.F and fulltosparse.F. To run this example, you need a supported Fortran compiler installed on your system.

Copy the source files to the current folder.


Build the fulltosparse MEX file. The MEX file name is fulltosparse because fulltosparse.F is the first file on the command line. The output contains information specific to your compiler.

mex -largeArrayDims fulltosparse.F loadsparse.F
Building with 'Intel Visual Fortran Composer XE 2013 with Microsoft Visual Studio 2012'.
MEX completed successfully.


full = eye(5);
spar = fulltosparse(full)
spar =

    1,1         1
    2,2         1
    3,3         1
    4,4         1
    5,5         1

Combine all C source files in the current folder into MEX file mymex. Use the -output option to control the name of the MEX file.

mex -output mymex *.c

To preview the build command details without executing the commands, use the -n option. The output contains information specific to your platform and compiler.

mex -n yprime.c

You can link to object files that you compile separately from your source MEX files.

The MEX file example fulltosparse consists of two Fortran source files. The fulltosparse file is the gateway routine (contains the mexFunction subroutine) and loadsparse contains the computational routine.

To run this example, you need a supported Fortran compiler installed on your system. Copy the computational subroutine to your current folder.


Compile the subroutine and place the object file in a separate folder, c:\objfiles.

mkdir c:\objfiles
mex -largeArrayDims -c -outdir c:\objfiles loadsparse.F
Building with 'Intel Visual Fortran Composer XE 2013 with Microsoft Visual Studio 2012'.
MEX completed successfully.

Copy the gateway subroutine to your current folder. Compile and link with the loadsparse object file.

mex -largeArrayDims fulltosparse.F c:\objfiles\loadsparse.obj
Building with 'Intel Visual Fortran Composer XE 2013 with Microsoft Visual Studio 2012'.
MEX completed successfully.

To specify the path to include the MATLAB LAPACK library subroutines for handling complex number routines, use the -I option. To use these subroutines, your MEX file must access the header file fort.h.

Copy the matrixDivideComplex.c example to the current folder.


Create the -I argument by concatenating '-I' with the path to fort.h file.

ipath = ['-I' fullfile(matlabroot,'extern','examples','refbook')];

Create variables for the names and paths to the LAPACK library file and the file, fort.c, containing the complex number handling routines.

lapacklib = fullfile(matlabroot,'extern','lib',computer('arch'),'microsoft','libmwlapack.lib');
fortfile = fullfile(matlabroot,'extern','examples','refbook','fort.c');

Build the MEX file.


Build the matrixDivide.c example on a Windows platform using the -L and -l options to specify the libmwlapack.lib library. The library file is located in the folder, matlabroot\extern\lib\arch\microsoft.

Copy the matrixDivide.c example to the current folder.


Capture the value of matlabroot.

ans =

C:\Program Files\MATLAB\R2014a

Capture the value of arch.

ans =


To build the MEX file, copy the values of matlabroot and arch into the mex command, as shown in the following statement.

mex '-LC:\Program Files\MATLAB\R2014a\extern\lib\win64\microsoft'...
   -llibmwlapack matrixDivide.c

You must use the ' characters because \Program Files in the path includes a space.

The mxcreatecharmatrixfromstr.c example uses a #define symbol SPACE_PADDING to determine what character to use between character vectors in a matrix. To set the value, build the MEX file with the -D option.

Copy the example to the current folder.


Set the SPACE_PADDING directive to add a space between values.

mex mxcreatecharmatrixfromstr.c -DSPACE_PADDING
Building with 'MinGW64 Compiler  C '.
MEX completed successfully.

Copy the engwindemo.c engine example to the current folder.

mex -client engine engwindemo.c

If you are running on a Windows platform, you must first register MATLAB as a COM server. For more information, see Register MATLAB as a COM Server.

Run the example.

mex -setup

MATLAB displays the options for your version and system based on the list of Supported and Compatible Compilers.

Input Arguments

collapse all

One or more file names, including name and file extension, specified as a string or character vector. If the file is not in the current folder, specify the full path to the file.

File names can be any combination of:

  • C, C++, or Fortran language source files

  • Simulink® S-function files

  • Object files

  • Static library files. For linking dynamic libraries, use the -llibname option.

The first source code file listed in filenames is the name of the binary MEX file. To override this naming convention, use the '-output' option.

Data Types: char

One or more build options, specified as one of these values. Options can appear in any order on any platform, except where indicated.



Uses Windows RSP file. An RSP file is a text file containing command-line options. Non-ASCII characters are not supported.


Compiles an object file only. Does not build a binary MEX file.

-client engine

Build engine application.


The -D options define C preprocessor macros. Equivalent to the following in the source file:

  • #define symbolname

  • #define symbolname symbolvalue

The -U option removes any initial definition of the C preprocessor macro, symbolname. Inverse of the -D option.

Do not add a space between D or U and symbolname. Do not add spaces around the = sign.

Example: Define Compiler Directive

-f filepath

To build engine applications, use the -client engine option.

Specifies name and location of the mex configuration file. Overrides the default compiler selection. For information about using a non-default compiler, see Change Default Compiler. filepath is the name and full path of the configuration file, specified as a string or character vector.


Adds symbolic information and disables optimizing built object code. Use for debugging. To debug with optimization, add the -O option.


Displays help for mex. Use from an operating system prompt.


Adds pathname to the list of folders to search for #include files.

Do not add a space between I and pathname.

Example: Specify Path to Include File

-Llibfolder -llibname

Links with dynamic object library libname in (optional) libfolder.

MATLAB expands libname to:

  • libname.lib or liblibname.lib — Windows systems

  • liblibname.dylibMac systems

  • — Linux systems

If used, the -L option must precede the -l option. When using the -L option on Linux or Mac systems, you also must set the runtime library path, as explained in Set Run-Time Library Path.

Do not add a space between l and libname or between L and libfolder.

Specify the -l option with the lowercase letter L.

To link a static library, use the filenames input argument.

Example: Specify Path to Library File


Displays, but does not execute, commands that mex would execute.

Example: Preview Build Commands


Optimizes the object code. Use this option to compile with optimization.

Optimization is enabled by default. Optimization is disabled when the -g option appears without the -O option.

Specify this option with the capital letter O.

-outdir dirname

Places all output files in folder dirname.

Example: Create and Link to Separate Object Files

-output mexname

Overrides the default MEX file naming mechanism. Creates binary MEX file named mexname with the appropriate MEX file extension.

Example: Combine Source Files Using Wildcard

-R2017b (default)

Links with the specified MATLAB array-handling C or Fortran Matrix API. Do not use this option for MEX files or engine applications using the MATLAB Data API.

  • -R2017b — Default option. -R2017b uses the -largeArrayDims option and treats a handle to a graphics object as object, not double.

  • -R2018a — Uses the interleaved complex API which includes the typed data access functions.

    To run a Fortran MEX file built with the interleaved complex API in MATLAB R2018a, you must use MATLAB R2018a Update 3.

  • -largeArrayDims — Uses the MATLAB large-array-handling API. This API handles arrays with more than 231-1 elements. Must use this option when calling LAPACK or BLAS functions.

  • -compatibleArrayDims — Uses the MATLAB Version 7.2 array-handling API, which limits arrays to 231-1 elements. Default option for C MEX S-functions only.

-setup lang

Change the default compiler to build lang language MEX files. When you use this option, mex ignores all other command-line options.


Suppresses informational messages. The mex command still reports errors and warnings, even when you specify -silent.


Removes any initial definition of the C preprocessor macro symbolname. (Inverse of the -D option.)

Do not add a space between U and symbolname.


Builds in verbose mode. Displays values for internal variables after all command-line arguments are considered. Displays each compile and link step fully evaluated. Use for troubleshooting compiler setup problems.

Example: Display Detailed Build and Troubleshooting Information


Overrides default setting for variable varname. This option is processed after all command-line arguments are considered.

Example: Override Default Compiler Switch Option.

Language, specified as one of these values.


C compilers, including C++.

C++ or CPP

C++ compilers.


Fortran compilers.


  • You can run mex from:

    • MATLAB Command Window

    • Windows system prompt

    • Mac Terminal

    • Linux shell

    For command-line usage outside of MATLAB, the mex program is located in the folder specified by [matlabroot '/bin'].

  • The MEX file has a platform-dependent extension. You can place binary MEX files for different platforms in the same folder.

    MEX File Platform-Dependent Extension

    PlatformBinary MEX File Extension

    Linux (64-bit)


    Apple Mac (64-bit)


    Windows (64-bit)


    To identify the MEX file extension, use the mexext function.

  • To use mex to build executable files for standalone MATLAB engine and MAT-file applications, use the -client engine option.

  • The mex command does not support folder names containing double quote (") characters.

Introduced before R2006a