Main Content

mex

Build MEX function or engine application

Description

example

mex filenames compiles and links one or more C++ source files written with the MATLAB Data API for C++ into a binary MEX file in the current folder. For information about writing these applications, see Write C++ Functions Callable from MATLAB (MEX Files).

If writing MEX files based on the C Matrix API or the Fortran Matrix API, then mex filenames builds one or more C, C++, or Fortran source files with the -R2017b api. In a future version of MATLAB®, the default api option will change to use the interleaved complex API (-R2018a). MathWorks recommends that you create MEX files and update existing MEX files to use the interleaved complex API. Alternatively, use the MX_HAS_INTERLEAVED_COMPLEX macro to apply the desired behavior across versions of MATLAB. For more information, see MATLAB Support for Interleaved Complex API in MEX Functions.

For information about working with C, C++, and Fortran applications, see Integrate MATLAB with External Programming Languages and Systems.

example

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

mex -client engine filenames builds C++ source files written with the MATLAB Data API for C++ into standalone MATLAB engine applications. For more information, see Elements of a C++ Engine Program.

If writing applications based on the MATLAB Engine API for C, the C MAT-File API, the Fortran Engine API, or the Fortran MAT-File API, then mex -client engine filenames builds a standalone application with the -R2017b api. In a future version of MATLAB, the default api option will change to use the interleaved complex API (-R2018a). MathWorks recommends that you create engine applications and update existing applications to use the interleaved complex API.

mex -client engine filenames api option1 ... optionN builds engine applications with the specified api and optional option1 ... optionN arguments.

mex -setup [lang] displays information about the default compiler for the given language for building MEX files. MATLAB defines a default compiler for each supported language. If you have multiple compilers for a given language, use the lang option to change the default compiler for that language. For more information, see Change Default Compiler and Choose a C++ Compiler.

mex -setup -client engine [lang] selects a compiler for building engine applications.

Examples

collapse all

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

copyfile(fullfile(matlabroot,'extern','examples','mex','explore.c'),'.','f')

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

mex -R2018a explore.c

Test the function by passing complex matrices.

a = [1 3 5];
b = [5 3 1];
A = complex(a,b);
explore(A)
------------------------------------------------
Name: prhs[0]
Dimensions: 1x3
Class Name: double
------------------------------------------------
	(1,1) = 1 + 5i
	(1,2) = 3 + 3i
	(1,3) = 5 + 1i

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

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

copyfile(fullfile(matlabroot,"extern","examples","mex","yprime.c"),".","f")

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

mex yprime.c
Building with 'Microsoft Visual C++ 2019 (C)'.
MEX completed successfully.

Test.

T=1;
Y=1:4;
yprime(T,Y)
ans = 1×4

    2.0000    8.9685    4.0000   -1.0947

To display the compile and link commands and other information useful for troubleshooting, use verbose mode. The output displays information specific to your platform and compiler.

mex -v -compatibleArrayDims yprime.c

Use environment variables to specify additional options to pass to a compiler.

Determine the variable name:

  • For building C++ code with MinGW®, macOS, and Linux® compilers, use CXXFLAGS.

  • For building C code with MinGW, macOS, and Linux compilers, use CFLAGS.

  • With Microsoft® Visual Studio® compilers, use COMPFLAGS.

Specify the C++17 standard when building a MEX file with Visual Studio.

mex COMPFLAGS='$COMPFLAGS -std=c++17' yprime.c

For more information about using string delimiters on different platforms, see Override Default Compiler Switch Option.

Build the yprime.c MEX file by appending the value -Wall to the existing compiler flags. 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 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. Choose one of these commands:

mex -v CXXFLAGS='$CXXFLAGS -Wall' yprime.c % C++ compiler
mex -v CFLAGS='$CFLAGS -Wall' yprime.c     % C compiler 

At the Windows® command prompt, use double quotes (").

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

At the shell command line on macOS 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.

copyfile(fullfile(matlabroot,'extern','examples','refbook','loadsparse.F'),'.','f')
copyfile(fullfile(matlabroot,'extern','examples','refbook','fulltosparse.F'),'.','f')

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.

Test.

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 displays 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.

copyfile(fullfile(matlabroot,'extern','examples','refbook','loadsparse.F'),'.','f')

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.

copyfile(fullfile(matlabroot,'extern','examples','refbook','fulltosparse.F'),'.','f')
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.

copyfile(fullfile(matlabroot,'extern','examples','refbook','matrixDivideComplex.c'),'.','f')

Create the -I argument by concatenating '-I' with the path to the 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.

mex('-v','-R2017b',ipath,'matrixDivideComplex.c',fortfile,lapacklib)

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.

copyfile(fullfile(matlabroot,'extern','examples','refbook','matrixDivide.c'),'.','f')

Capture the value of matlabroot displayed by this statement to use in the mex command.

matlabroot
ans =

C:\Program Files\MATLAB\R2014a

Capture the value of arch displayed by this statement to use in the mex command.

computer('arch')
ans =

win64

To build the MEX file, copy the values of matlabroot and arch into the mex command.

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.

copyfile(fullfile(matlabroot,'extern','examples','mx','mxcreatecharmatrixfromstr.c'),'.','f')

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.

copyfile(fullfile(matlabroot,'extern','examples','eng_mat','engwindemo.c'),'.','f')

Build a standalone MATLAB engine application using the -client engine syntax.

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.

!engwindemo
mex -setup

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

To add options to the mex link command, use the LINKFLAGS command line option. For example, to specify the environment for the executable when building mymex.c on Windows, type:

mex -v LINKFLAGS='$LINKFLAGS /subsystem:windows' mymex.c

Input Arguments

collapse all

One or more file names, including name and file extension, specified as a string or a 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 source files.

  • Simulink® S-function files.

  • Object files.

  • Static library files. filenames must include the fully qualified path to the library file. The library must be compiled with the same compiler currently used by mex.

    To link dynamic libraries, use the -llibname option.

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

Use the MATLAB Editor to write your source code. If you use an integrated development environment (IDE) such as Microsoft Visual Studio or Xcode, then you can use the mex command or follow the guidelines in Custom Build with MEX Script Options.

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

Links with the release-specific C Matrix API or Fortran Matrix API, specified as one of the values in the table. Do not combine these options.

Do not use this option for MEX files or engine applications using the MATLAB Data API for C++.

APIDescription

-R2017b (default)

Builds with:

  • Separate complex API, which contains the C and Fortran Matrix API functionality in MATLAB R2017b and earlier.

  • Large-array-handling API, which handles arrays with more than 231–1 elements.

  • Treating a handle to a graphics object as object, not double.

In a future version of MATLAB, the default api option will change to use the interleaved complex API (-R2018a). MathWorks recommends that you create applications and update existing applications to use the interleaved complex API. Alternatively, use the MX_HAS_INTERLEAVED_COMPLEX macro to apply the desired behavior across versions of MATLAB. For more information, see MATLAB Support for Interleaved Complex API in MEX Functions.

-R2018a

Builds with:

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

-largeArrayDims

Builds with:

  • Separate complex API

  • Large-array-handling API

  • Treating a handle to a graphics object as object, not double. To treat the handle as double, combine this option with -DMEX_DOUBLE_HANDLE.

-compatibleArrayDims

Builds with:

  • Separate complex API

  • Version 7.2 array-handling API, which limits arrays to 231–1 elements

  • Treating a handle to a graphics object as object, not double. To treat the handle as double, combine this option with -DMEX_DOUBLE_HANDLE.

Do not use the -compatibleArrayDims option when calling LAPACK or BLAS functions.

Default option for C MEX S-functions only.

Example: mex -R2018a explore.c

Optional build options, specified as one of the values in this table. Options can appear in any order on any platform, except where indicated.

OptionDescription

@rspfile

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

-c

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

-client engine

Builds an engine application.

-Dsymbolname
-Dsymbolname=symbolvalue
-Usymbolname

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

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

Do not use the -f option to build engine applications. Use the -client engine option instead.

-g

Adds symbolic information and disables optimization of built object code. Use for debugging.

-h[elp]

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

-Ipathname

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

-llibname
-Llibfolder -llibname

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

MATLAB expands libname to:

  • libname.lib or liblibname.lib — Windows systems

  • liblibname.dylibmacOS systems

  • liblibname.so — Linux systems

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

Specify the -l option with the lowercase letter L. Do not add a space between l and libname or between L and libfolder.

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

Example: Specify Path to Library File

-n

Displays but does not execute commands that mex would execute.

Example: Preview Build Commands

-O

Optimizes the object code. Use this option to compile with optimization. Optimization is enabled by default.

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 a binary MEX file named mexname with the appropriate MEX file extension.

Example: Combine Source Files Using Wild Card

-setup lang

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

-silent

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

-Usymbolname

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

Do not add a space between U and symbolname.

-v

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

varname=varvalue

Append values to environment variable varname. This option is processed after all command-line arguments are considered.

Examples:

Language, specified as one of these case-insensitive values.

C

C compilers, including C++

C++ or CPP

C++ compilers

Fortran

Fortran compilers

Tips

  • You can run mex from:

    • MATLAB Command Window

    • Windows system prompt

    • macOS Terminal

    • Linux shell

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

  • The MEX file has a platform-dependent extension. You can place binary MEX files for different platforms in the same folder. To identify the MEX file extension, use the mexext function.

    MEX File Platform-Dependent Extension

    PlatformBinary MEX File Extension

    Windows

    mexw64

    Linux

    mexa64

    macOS with Apple silicon

    mexmaca64

    macOS with Intel®

    mexmaci64

    Note

    MEX files built on macOS with Intel are not supported on the Apple silicon platform using Rosetta 2.

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

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

Version History

Introduced before R2006a

expand all