Quantcast

Documentation Center

  • Trial Software
  • Product Updates

mex

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

Syntax

  • mex -setup lang

Description

example

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.

example

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 when you want to change the default compiler for the given language.

Examples

expand all

Build C MEX-File

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

Each example is based on MEX examples in the matlabroot/extern/examples subfolders. To build the example code, copy the source file to a writable folder on your path, such as c:\work. Set the current folder to c:\work.

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

Copy the source code, yprime.c.

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

Build the MEX-file.

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

The output displays information specific to your compiler.

Test.

T=1; Y=1:4;
yprime(T,Y)
ans =
     2.0000   8.9685   4.0000    -1.0947

Build MEX-File from Multiple Source Files

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.

mex -largeArrayDims fulltosparse.F loadsparse.F

The MEX-file name is fulltosparse because fulltosparse.F is the first file on the command line.

Test.

full = eye(5);
spar = fulltosparse(full)
spar =
   (1,1)        1
   (2,2)        1
   (3,3)        1
   (4,4)        1
   (5,5)        1

Preview Build Commands

To preview the build command details without executing the commands, use the -n option.

mex -n yprime.c

The output displays information specific to your platform and compiler.

Display Detailed Build and Troubleshooting Information

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.

Create and Link to Separate Object Files

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, loadsparse.F and fulltosparse.F. 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

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

Specify Path to Include File

Use the -I option to specify the path to include the MATLAB LAPACK library subroutines for handling complex number routines. 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 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','-largeArrayDims',ipath, ...
    'matrixDivideComplex.c',fortfile,lapacklib)

Specify Path to Library File

Build the matrixDivide.c example on a Windows® platform.

Use the -L and -l options to specify the libmwlapack.lib library, 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.

matlabroot
ans =

C:\Program Files\MATLAB\R2014a

Capture the value of arch.

arch
ans =

win64

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

mex -largeArrayDims '-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.

Define Directive

Define the character to use between strings in a matrix.

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

Copy the mxcreatecharmatrixfromstr.c example to the current folder.

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

Set the SPACE_PADDING directive to add a space between strings.

mex mxcreatecharmatrixfromstr.c -DSPACE_PADDING

Override Default Compiler Switch Option

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

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

Build Engine Application

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

copyfile(fullfile(matlabroot,...
  'extern','examples','eng_mat','engwindemo.c'),'.','f');
mex -client engine engwindemo.c

Run the example.

!engwindemo

Select C Compiler

mex -setup

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

Input Arguments

expand all

filenames — One or more file namesstring

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

  • library files

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

Data Types: char

option1 ... optionN — One or more build optionsstrings corresponding to valid option flags

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

OptionDescription

@rspfile

Uses Windows RSP file. An RSP file is a text file containing command-line options.

-c

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

-client engine

Build engine application.

-compatibleArrayDims
(default)
-largeArrayDims

Links with the specified MATLAB array-handling API.

  • -compatibleArrayDims — Uses the MATLAB Version 7.2 array-handling API, which limits arrays to 231-1 elements. Default option.

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

In verbose mode (-v option), if you do not specify either the -compatibleArrayDims or the -largeArrayDims option, MATLAB displays a message showing the default option.

-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 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 Changing Default Compiler. filepath is the name and full path of the configuration file, specified as a string.

-g

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

-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 object library libname in (optional) libfolder.

MATLAB expands libname to:

  • libname.lib or liblibname.lib — Windows systems

  • liblibname.dylib — Mac systems

  • liblibname.so — 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 Setting 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.

Example: Specify Path to Library File

-largeArrayDims
-compatibleArrayDims
(default)

Links with the specified MATLAB array-handling API.

  • -compatibleArrayDims — Uses the MATLAB Version 7.2 array-handling API, which limits arrays to 231-1 elements. Default option.

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

In verbose mode (-v option), if you do not specify either the -compatibleArrayDims or the -largeArrayDims option, MATLAB displays a message showing the default option.

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

-setup lang

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

-silent

Suppresses informational messages. The mex function still reports errors and warnings, even 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.

Example: Display Detailed Build and Troubleshooting Information

varname=varvalue

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

Example: Override Default Compiler Switch Option.

lang — LanguageC (default) | C++ | CPP | Fortran

Language, specified as one of these values.

C

C compilers, including C++.

C++ or CPP

C++ compilers.

Fortran

Fortran compilers.

More About

expand all

Tips

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

    PlatformBinary MEX-File Extension

    Linux (64-bit)

    mexa64

    Apple Mac (64-bit)

    mexmaci64

    Microsoft® Windows (32-bit)

    mexw32

    Windows (64-bit)

    mexw64

    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.

See Also

| | | | | | | | | | |

Was this topic helpful?