compiler
compiler
MATLAB Compiler
The Language of Technical Computing
Computation
Visualization
Programming
User’s Guide
Version 2.1
How to Contact The MathWorks:
508-647-7000 Phone
508-647-7001 Fax
http://www.mathworks.com Web
ftp.mathworks.com Anonymous FTP server
comp.soft-sys.matlab Newsgroup
i
UNIX Workstation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
mex Verification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
MATLAB Compiler Verification . . . . . . . . . . . . . . . . . . . . . . . . 2-12
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-26
mex Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-26
Troubleshooting the Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . 2-28
ii Contents
Stand-Alone Applications
4
Differences Between MEX-Files
and Stand-Alone Applications . . . . . . . . . . . . . . . . . . . . . . . . . 4-3
Stand-Alone C Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3
Stand-Alone C++ Applications . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-28
Troubleshooting mbuild . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-28
Troubleshooting the Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . 4-29
iii
Mixing M-Files and C or C++ . . . . . . . . . . . . . . . . . . . . . . . . . . 4-37
Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-37
Advanced C Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-42
iv Contents
Including M-File Information in Compiler Output . . . . . . 5-34
Controlling Comments in Output Code . . . . . . . . . . . . . . . . . . 5-34
Controlling #line Directives in Output Code . . . . . . . . . . . . . . 5-36
Controlling Information in Run-Time Errors . . . . . . . . . . . . . . 5-38
Optimizing Performance
6
Optimization Bundles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
v
Reference
7
Pragmas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4
%#external . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-5
%#function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6
%#mex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8
mbchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9
mbcharscalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10
mbcharvector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-11
mbint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-12
mbintscalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-14
mbintvector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-15
mbreal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-16
mbrealscalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-17
mbrealvector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-18
mbscalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-19
mbvector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-20
reallog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-21
realpow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-22
realsqrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-23
mcc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4
vi Contents
Error and Warning Messages
B
Compile-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-3
vii
viii Contents
1
Introducing the
MATLAB Compiler
Introduction . . . . . . . . . . . . . . . . . . . . 1-2
Before You Begin . . . . . . . . . . . . . . . . . . . 1-2
New Features . . . . . . . . . . . . . . . . . . . . 1-3
Compiler Licensing Changes . . . . . . . . . . . . . . 1-5
Introduction
This book describes version 2.1 of the MATLAB® Compiler. The MATLAB
Compiler takes M-files as input and generates C or C++ source code or P-code
as output. The MATLAB Compiler can generate these kinds of source code:
This chapter takes a closer look at these categories of C and C++ source code
and explains the value of compiled code.
Note The phrase MATLAB interpreter refers to the application that accepts
MATLAB commands, executes M-files and MEX-files, and behaves as
described in Using MATLAB. When you use MATLAB, you are using the
MATLAB interpreter. The phrase MATLAB Compiler refers to this product
that translates M-files to C or C++ source code. This book distinguishes
references to the MATLAB Compiler by using the word ‘Compiler’ with a
capital C. References to ‘compiler’ with a lowercase c refer to your C or C++
compiler.
1-2
New Features
MATLAB Compiler 2.1 supports much of the functionality of MATLAB 6. The
new features of the Compiler are:
• Optimizations
• mlib files
• Additional data type support
• Improved support for load and save
• Dynamically linking in MEX-files in the stand-alone environment
• MATLAB add-in for Visual Studio
• Faster C/C++ Math Library applications
• Additional language support
Note The MATLAB Compiler 2.1 does not support user-defined classes
(MATLAB objects), scripts, or calls to the MATLAB Java interface.
Optimizations
Compiler 2.1 provides a series of optimizations that can help speed up your
compiled code. These optimizations are on by default unless you are building a
debuggable version.
Folding Array Constants. Folds scalar and nonscalar valued array constants.
One- and Two-Dimensional Array Indexing. Uses faster routines that are optimized
for simple indexing.
1-3
1 Introducing the MATLAB Compiler
mlib Files
mlib files make it possible to produce a shared library out of a toolbox and then
compile M-files that make calls into that toolbox. Specifying an mlib file tells
the MATLAB Compiler to link against the mlib file’s corresponding shared
library whenever it needs to use any of the functions found in that library. The
mlib file and its corresponding shared library file must be located within the
same directory. For more information about mlib files, see “mlib Files” on page
5-25.
Integer Data Types. The signed and unsigned integer arrays int8, int16, int32,
uint8, uint16, and uint32 are now supported, which provides improved
support for the Image Processing Toolbox.
Function Handles. A function handle is a new MATLAB data type that captures
all the information about a function that MATLAB needs to evaluate it.
Compiler 2.1 supports function handles. For more information on function
handles, see the function handle reference page.
1-4
Additional Language Support
eval and input. eval and input are supported for strings that do not contain
workspace variables.
1-5
1 Introducing the MATLAB Compiler
• Does not require MATLAB to be running on the system where the Compiler
is running
• Gives the user a dedicated 30 minute time allotment during which the user
has complete ownership over a license to the Compiler
Each time a user requests the Compiler, the user begins a 30 minute time
period as the sole owner of the Compiler license. Anytime during the 30 minute
segment, if the same user requests the Compiler, the user gets a new 30 minute
allotment. When the 30-minute time interval has elapsed, if a different user
requests the Compiler, the new user gets the next 30 minute interval.
When a user requests the Compiler and a license is not available, the user
receives the message
Error: Could not check out a Compiler License.
This message is given when no licenses are available. As long as licenses are
available, the user gets the license and no message is displayed. The best way
to guarantee that all MATLAB Compiler users have constant access to the
Compiler is to have an adequate supply of licenses for your users.
1-6
Uses of the Compiler
Note MEX-files generated by the MATLAB Compiler 2.1 are not backward
compatible. They require MATLAB 6/Release 12 or greater.
Creating MEX-Files
The MATLAB Compiler, when invoked with the -x macro option, produces a
MEX-file from M-files. The Compiler:
3 Invokes the mex utility which builds the C MEX-file source into a MEX-file
by linking the MEX-file with the MEX version of the math libraries
(libmatlbmx).
1-7
1 Introducing the MATLAB Compiler
M-File
mcc -x
MEX-File
MATLAB users who do not have the MATLAB Compiler must write the source
code for MEX-files in either Fortran or C. “External Interfaces/API” explains
the fundamentals of this process. To write MEX-files, you have to know how
MATLAB represents its supported data types and the MATLAB external
interface (i.e., the application program interface, or API.)
If you are comfortable writing M-files and have the MATLAB Compiler, then
you do not have to learn all the details involved in writing MEX-file source
code.
1-8
Uses of the Compiler
Note If you do not have the MATLAB C/C++ Graphics Library (libsgl), and
your application calls a Handle Graphics function, a run-time error occurs.
1-9
1 Introducing the MATLAB Compiler
mcc -m
Object Files
Linker
Stand-Alone
C Application
1-10
Uses of the Compiler
Note The MATLAB Compiler contains a tool, mbuild, which simplifies much
of this process. Chapter 4, “Stand-Alone Applications,” describes the mbuild
tool.
-p and -m are examples of options that you use to control how the Compiler
works. The “Reference” chapter includes a complete description of the Compiler
2.1 options in the section, “mcc.” Throughout this book you will see numerous
examples of how these options are used with the Compiler to perform various
tasks.
1-11
1 Introducing the MATLAB Compiler
M-File(s)
MAIN 1 1
MEX 2
LIB 3 3
Simulink 4
MATLAB C/C++
User C/C++ Code C/C++ Compiler Math Library
1 2 3 4
Target Types
1-12
The MATLAB Compiler Family
The Compiler takes your M-file(s) and can generate C or C++ code. It can also
generate one of four wrapper files depending on your specified target. This
table shows the wrapper files the Compiler can generate, their associated
targets, and the corresponding -W option (wrapper).
1-13
1 Introducing the MATLAB Compiler
Faster Execution
Compiled C or C++ code typically runs faster than its M-file equivalents
because:
1-14
Why Compile M-Files?
Cases When Performance Does Not Improve. Compilation is not likely to speed up
M-file functions that:
1-15
1 Introducing the MATLAB Compiler
Installation
The MATLAB 6 (Release 12) installer automatically installs Compiler 2.1.
Once you install and configure Compiler 2.1, you can compile your M-files from
either the MATLAB prompt or the DOS or UNIX command line. For more
information about installation, see Chapter 2, “Installation and
Configuration.”
In C++, beginning with MATLAB 5.0, the name of the basic MATLAB data
type, mwMatrix, has changed. The new name for the data type is mwArray.
1-16
Limitations and Restrictions
Note input and eval calls that do not use workspace variables will compile
and execute properly.
1-17
1 Introducing the MATLAB Compiler
Stand-Alone Applications
The restrictions and limitations noted in the previous section also apply to
stand-alone applications. The functions in this table are supported in
MEX-mode, but are not supported in stand-alone mode.
Note You cannot call any Handle Graphics functions unless you have the
optional Graphics Library installed. In addition, stand-alone applications
cannot access Simulink functions. Although the MATLAB Compiler can
compile M-files that call these functions, the MATLAB C/C++ Math library
does not support them. Therefore, unless you write your own versions of the
unsupported routines in a MEX-file or as C-code, when you run the
executable, you will get a run-time error.
1-18
Limitations and Restrictions
whos
1-19
1 Introducing the MATLAB Compiler
1-20
2
Installation and
Configuration
System Configuration for MEX-Files . . . . . . . . . 2-3
Troubleshooting . . . . . . . . . . . . . . . . . . 2-26
mex Troubleshooting . . . . . . . . . . . . . . . . . 2-26
Troubleshooting the Compiler . . . . . . . . . . . . . 2-28
2 Installation and Configuration
2-2
System Configuration for MEX-Files
2 Install an ANSI C or C++ compiler, if you don’t already have one installed.
4 Verify that the MATLAB Compiler can generate MEX-files from the
MATLAB command line and from the UNIX or DOS command line.
This figure shows the Compiler installation sequence for creating MEX-files on
both platforms. The sections following the flowchart provide more specific
details for the individual platforms. Additional steps may be necessary if you
plan to create stand-alone applications or libraries, however, you still must
perform the steps given in this chapter first. Chapter 4, “Stand-Alone
Applications” provides the details about the additional installation and
configuration steps necessary for creating stand-alone applications and
libraries.
2-3
2 Installation and Configuration
Start
Yes 1
2
1
Verify MATLAB
Compiler can Test your Does the MATLAB command No
generate
MEX-files from MATLAB Compiler mcc invhilb.m
MATLAB/DOS/ installation/configuration. generate invhilb.mex
UNIX command ?
line
See “Compiler
Yes Troubleshooting.”
Stop
2
2-4
UNIX Workstation
UNIX Workstation
This section examines the system requirements, installation procedures, and
configuration procedures for the MATLAB Compiler on UNIX systems.
System Requirements
You cannot install the MATLAB Compiler unless MATLAB 6/Release 12 is
already installed on the system. The MATLAB Compiler imposes no operating
system or memory requirements beyond those that are necessary to run
MATLAB. The MATLAB Compiler consumes a small amount of disk space.
This table shows the requirements for creating UNIX applications with the
MATLAB Compiler.
Note If your application uses Handle Graphics, you will need the MATLAB
C/C++ Graphics Library to develop stand-alone applications. The MATLAB C/
C++ Graphics Library is a separately sold product.
2-5
2 Installation and Configuration
Note For a list of all the compilers supported by MATLAB, see the
MathWorks Technical Support Department’s Technical Notes at:
http://www.mathworks.com/support/tech-notes/v5/1600/1601.shtml
Known Compiler Limitations. There are several known restrictions regarding the
use of supported compilers:
2-6
UNIX Workstation
shows the preconfigured options files that are included with MATLAB for
UNIX.
Information on the options files is provided for those users who may need to
modify them to suit their own needs. Many users never have to be concerned
with the inner workings of the options files.
Installation
MATLAB Compiler
To install the MATLAB Compiler on UNIX systems, follow the instructions in
the MATLAB Installation Guide for UNIX. If you have a license to install the
MATLAB Compiler, it appears as one of the installation choices that you can
select as you proceed through the installation process. If the MATLAB
Compiler does not appear as one of the installation choices, contact The
MathWorks to get an updated license file (license.dat):
2-7
2 Installation and Configuration
Things to Be Aware of
This table provides information regarding the installation and configuration of
a C or C++ compiler on your system.
Description Comment
mex Verification
Choosing a Compiler
Using the System Compiler. If the MATLAB Compiler and your supported C or
C++ compiler are installed on your system, you are ready to create C MEX-files.
To create a MEX-file, you can simply enter
mex filename.c
This simple method of creating MEX-files works for the majority of users. It
uses the system’s compiler as your default compiler for creating C MEX-files.
2-8
UNIX Workstation
If you do not need to change C or C++ compilers, or you do not need to modify
your compiler options files, you can skip ahead in this section to “Creating
MEX-Files” on page 2-10. If you need to know how to change the options file,
continue with this section.
Changing Compilers
Changing the Default Compiler. To change your default C or C++ compiler, you
select a different options file. You can do this at anytime by using the command
mex -setup
To override the default options file, use the 'mex -f' command
(see 'mex -help' for more information).
1: <matlab>/bin/gccopts.sh :
Template Options file for building gcc MEX-files
2: <matlab>/bin/mexopts.sh :
Template Options file for building MEX-files via the
system ANSI compiler
Enter the number of the options file to use as your default options
file:
Select the proper options file for your system by entering its number and
pressing Return. If an options file doesn’t exist in your MATLAB directory, the
system displays a message stating that the options file is being copied to your
user-specific matlab directory. If an options file already exists in your
MATLAB directory, the system prompts you to overwrite it.
2-9
2 Installation and Configuration
Using the setup option resets your default compiler so that the new compiler
is used every time you use the mex script.
Modifying the Options File. Another use of the setup option is if you want to
change your options file settings. For example, if you want to make a change to
the current linker settings, or you want to disable a particular set of warnings,
you should use the setup option.
As the previous note says, setup copies the appropriate options file to your
individual directory. To make your user-specific changes to the options file, you
then edit your copy of the options file to correspond to your specific needs and
save the modified file. This sets your default compiler’s options file to your
specific version.
The -f option tells the mex script to use the options file, <file>. If <file> is not
in the current directory, then <file> must be the full pathname to the desired
options file. Using the -f option tells the mex script to use the specified options
file for the current execution of mex only; it does not reset the default compiler.
Creating MEX-Files
To create MEX-files on UNIX, first copy the source file(s) to a local directory,
and then change directory (cd) to that local directory.
2-10
UNIX Workstation
HP-UX mexhpux
Linux mexglx
SGI mexsg
Solaris mexsol
This should create the MEX-file called yprime with the appropriate extension
corresponding to your UNIX platform. For example, if you create the MEX-file
on Solaris, its name is yprime.mexsol.
You can now call yprime from the MATLAB prompt as if it were an M-function.
For example,
yprime(1,1:4)
ans =
2.0000 8.9685 4.0000 -1.0947
2-11
2 Installation and Configuration
After a short delay, this command should complete and display the MATLAB
prompt. Next, at the MATLAB prompt, type
which invhilb
The which command should indicate that invhilb is now a MEX-file by listing
the filename followed by the appropriate UNIX MEX-file extension. For
example, if you run the Compiler on Solaris, the Compiler creates the file
invhilb.mexsol. Finally, at the MATLAB prompt, type
invhilb(10)
Note that this tests only the Compiler’s ability to make MEX-files. If you want
to create stand-alone applications, refer to Chapter 4, “Stand-Alone
Applications” for additional details.
Note Before you test to see if the Compiler can generate MEX-files from the
UNIX command prompt, you may want to delete the MEX-file you created in
the previous section, invhilb.mexsol, or whatever the extension is on your
system. That way, you can be sure your newly generated MEX-file is the
result of using the Compiler from the UNIX prompt.
2-12
UNIX Workstation
Next, verify that invhilb is now a MEX-file by listing the invhilb files.
ls invhilb.*
These are the various files that the Compiler generates from the M-file. The
Compiler-generated MEX-file appears in the list as the filename followed by
the appropriate UNIX MEX-file extension. In this example, the Compiler was
executed on Solaris, so the Compiler creates the file invhilb.mexsol. For more
information on which files the Compiler creates for a compilation, see Chapter
5, “Controlling Code Generation.”
To test the newly created MEX-file, start MATLAB and, at the MATLAB
prompt, type
invhilb(10)
2-13
2 Installation and Configuration
System Requirements
You cannot install the MATLAB Compiler unless MATLAB 6/Release 12 is
already installed on the system. The MATLAB Compiler imposes no operating
system or memory requirements beyond what is necessary to run MATLAB.
The MATLAB Compiler consumes a small amount of disk space.
This table shows the requirements for creating PC applications with the
MATLAB Compiler.
Note MATLAB includes an ANSI C compiler (Lcc) that is suitable for use
with the MATLAB Compiler.
The MATLAB C/C++ Math Library is a separately sold product; the MATLAB
C/C++ Graphics Library is a separately sold product. If your application uses
Handle Graphics, you will need the MATLAB C/C++ Graphics Library to
develop stand-alone applications.
2-14
Microsoft Windows on PCs
Note For a list of all the compilers supported by MATLAB, see the
MathWorks Technical Support Department’s Technical Notes at:
http://www.mathworks.com/support/tech-notes/v5/1600/1601.shtml
To create stand-alone applications or DLLs, you also need the MATLAB C/C++
Math Library, which is sold separately. Also, if your applications use Handle
Graphics, you will need the MATLAB C/C++ Graphics Library, which is sold
separately.
Applications generated by the MATLAB Compiler are 32-bit applications and
only run on Windows 95/98/2000 and Windows NT systems.
Known Compiler Limitations. There are several known restrictions regarding the
use of supported compilers:
2-15
2 Installation and Configuration
• The MATLAB Compiler 2.1 sometimes will generate goto statements for
complicated if conditions. The Borland C++ Compiler prohibits the goto
statement within a try…catch block. This error can occur if you use the
-A debugline:on option, because its implementation uses try…catch. To
work around this limitation, simplify the if conditions.
• There is a limitation with the Borland C++ Compiler. In your M-code, if you
use a constant number that includes a leading zero and contains the digit ‘8’
or ‘9’ before the decimal point, the Borland compiler will display the error
message
Error <file>.c <line>: Illegal octal digit in function
<functionname>
For example, the Borland compiler considers 009.0 an illegal octal integer as
opposed to a legal floating-point constant, which is how it is defined in the
ANSI C standard.
As an aside, if all the digits are in the legal range for octal numbers (0-7),
then the compiler will incorrectly treat the number as a floating-point value.
So, if you have code such as
x = [007 06 10];
and want to use the Borland compiler, you should edit the M-code to remove
the leading zeros and write it as
x = [7 6 10];
2-16
Microsoft Windows on PCs
mex uses the first occurrence of the options file it finds. If no options file is
found, mex searches your machine for a supported C compiler and uses the
factory default options file for that compiler. If multiple compilers are found,
you are prompted to select one.
The User Profile Directory Under Windows. The Windows user profile directory is
a directory that contains user-specific information such as desktop appearance,
recently used files, and Start menu items. The mex and mbuild utilities store
their respective options files, mexopts.bat and compopts.bat, which are
2-17
2 Installation and Configuration
Installation
MATLAB Compiler
To install the MATLAB Compiler on a PC, follow the instructions in the
MATLAB Installation Guide for PC. If you have a license to install the
MATLAB Compiler, it will appear as one of the installation choices that you
can select as you proceed through the installation process.
If the Compiler does not appear in your list of choices, contact The MathWorks
to obtain an updated License File (license.dat) for multiuser network
installations, or an updated Personal License Password (PLP) for single-user,
standard installations:
2-18
Microsoft Windows on PCs
Things to Be Aware of
This table provides information regarding the installation and configuration of
a C/C++ compiler on your system.
Description Comment
Running from the Make sure you select all relevant options for
command line running your compiler from the command line.
2-19
2 Installation and Configuration
mex Verification
Choosing a Compiler
Systems with Exactly One C/C++ Compiler. If you have properly installed the
MATLAB Compiler and your supported C or C++ compiler, you can now create
C MEX-files. On systems where there is exactly one C or C++ compiler
available to you, the mex utility automatically configures itself for the
appropriate compiler. So, for many users, to create a C MEX-file, you can
simply enter
mex filename.c
This simple method of creating MEX-files works for the majority of users. It
uses your installed C or C++ compiler as your default compiler for creating your
MEX-files.
If you are a user who does not need to change compilers, or you do not need to
modify your compiler options files, you can skip ahead in this section to
“Creating MEX-Files” on page 2-23.
Note On Windows 95 and Windows 98 systems, if you get the error, out of
environment space, see “Out of Environment Space Running mex or mbuild”
on page 2-26 for more information.
Systems with More than One C/C++ Compiler. On systems where there is more than
one C or C++ compiler, the mex utility lets you select which of the compilers you
want to use. Once you choose your C or C++ compiler, that compiler becomes
your default compiler and you no longer have to select one when you compile
MEX-files.
For example, if your system has both the Borland and Watcom compilers, when
you enter for the first time
mex filename.c
2-20
Microsoft Windows on PCs
[0] : None
Changing Compilers
Changing the Default Compiler. To change your default C or C++ compiler, you
select a different options file. You can do this at any time by using the
mex -setup option.
This example shows the process of changing your default compiler to the
Microsoft Visual C/C++ Version 6.0 compiler.
mex -setup
Select a compiler:
[1] Borland C++Builder version 5.0
[2] Borland C++Builder version 4.0
[3] Borland C++Builder version 3.0
[4] Borland C/C++ version 5.02
[5] Borland C/C++ version 5.0
[6] Borland C/C++ (free command line tools) version 5.5
[7] Compaq Visual Fortran version 6.1
[8] Digital Visual Fortran version 6.0
[9] Digital Visual Fortran version 5.0
[10] Lcc C version 2.4
[11] Microsoft Visual C/C++ version 6.0
[12] Microsoft Visual C/C++ version 5.0
[13] WATCOM C/C++ version 11
[14] WATCOM C/C++ version 10.6
2-21
2 Installation and Configuration
[0] None
Compiler: 11
Updated ...
If the specified compiler cannot be located, you are given the message:
The default location for compiler-name is directory-name,
but that directory does not exist on this machine.
Use directory-name anyway [y]/n?
Using the setup option sets your default compiler so that the new compiler is
used everytime you use the mex script.
Modifying the Options File. Another use of the setup option is if you want to
change your options file settings. For example, if you want to make a change to
the current linker settings, or you want to disable a particular set of warnings,
you should use the setup option.
The setup option copies the appropriate options file to your user profile
directory. To make your user-specific changes to the options file, you edit your
2-22
Microsoft Windows on PCs
copy of the options file in your user profile directory to correspond to your
specific needs and save the modified file. After completing this process, the mex
script will use the new options file everytime with your modified settings.
The -f option tells the mex script to use the options file, <file>. If <file> is not
in the current directory, then <file> must be the full pathname to the desired
options file. Using the -f option tells the mex script to use the specified options
file for the current execution of mex only; it does not reset the default compiler.
Creating MEX-Files
The <matlab>\extern\examples\mex directory contains C source code for the
example yprime.c. To verify that your system can create MEX-files, enter at
the MATLAB prompt
cd([matlabroot '\extern\examples\mex'])
mex yprime.c
Using an IDE
The MathWorks provides a MATLAB add-in for the Visual Studio development
system that lets you work easily within Microsoft Visual C/C++ (MSVC)
environment to create and debug MEX-files. The MATLAB add-in for Visual
Studio is included with MATLAB and is automatically installed when you run
mex -setup and select Microsoft Visual C/C++ version 5 or 6. For more
2-23
2 Installation and Configuration
After a short delay, this command should complete and display the MATLAB
prompt. Next, at the MATLAB prompt, type
which invhilb
The which command should indicate that invhilb is now a MEX-file; it should
have created the file invhilb.dll. Finally, at the MATLAB prompt, type
invhilb(10)
Note that this tests only the Compiler’s ability to make MEX-files. If you want
to create stand-alone applications or DLLs, refer to Chapter 4, “Stand-Alone
Applications,” for additional details.
Note Before you test to see if the Compiler can generate MEX-files from the
DOS command prompt, you may want to delete the MEX-file you created in
the previous section, invhilb.dll. That way, you can be sure your newly
generated MEX-file is the result of using the Compiler from the DOS prompt.
To delete this file, you must clear the MEX-file or quit MATLAB; otherwise
the deletion will fail.
2-24
Microsoft Windows on PCs
Next, verify that invhilb is now a MEX-file by listing the invhilb files.
dir invhilb*
These are the files that the Compiler generates from the M-file, in addition to
the original M-file, invhilb.m. The Compiler-generated MEX-file appears in
the list as the filename followed by the extension, dll. In this example, the
Compiler creates the file invhilb.dll. For more information on which files the
Compiler creates for a compilation, see Chapter 5, “Controlling Code
Generation.”
To test the newly created MEX-file, you would start MATLAB and, at the
MATLAB prompt, you could type
invhilb(10)
2-25
2 Installation and Configuration
Troubleshooting
This section identifies some of the more common problems that can occur when
installing and configuring the MATLAB Compiler.
mex Troubleshooting
Out of Environment Space Running mex or mbuild. On Windows 95 and Windows 98
systems, the mex and mbuild scripts require more than the default amount of
environment space. If you get the error, out of environment space, add this
line to your config.sys file.
shell=c:\command.com /e:32768 /p
DLLs Not on Path on Windows. MATLAB will fail to load MEX-files if it cannot find
all DLLs referenced by the MEX-file; the DLLs must be on the DOS path or in
the same directory as the MEX-file. This is also true for third-party DLLs.
Generates Wrong Answers. If your program generates the wrong answer(s), there
are several possible causes. There could be an error in the computational logic
or there may be a defect in the MATLAB Compiler. Run your original M-file
with a set of sample data and record the results. Then run the associated
MEX-file with the sample data and compare the results with those from the
original M-file. If the results are the same, there may be a logic problem in your
original M-file. If the results differ, there may be a defect in the MATLAB
Compiler. In this case, send the pertinent information via e-mail to
[email protected].
mex Works from Shell But Not from MATLAB (UNIX). If the command
mex -x yprime.c
2-26
Troubleshooting
works from the UNIX shell prompt but does not work from the MATLAB
prompt, you may have a problem with your .cshrc file. When MATLAB
launches a new C shell to perform compilations, it executes the .cshrc script.
If this script causes unexpected changes to the PATH, an error may occur. You
can test whether this is true by performing a
set SHELL=/bin/sh
prior to launching MATLAB. If this works correctly, then you should check
your .cshrc file for problems setting the PATH.
Cannot Locate Your Compiler (PC). If mex has difficulty locating your installed
compilers, it is useful to know how it goes about finding compilers. mex
automatically detects your installed compilers by first searching for locations
specified in the following environment variables.
Next, mex searches the Windows Registry for compiler entries. Note that
Watcom does not add an entry to the registry. Digital Fortran does not use an
environment variable; mex only looks for it in the registry.
Internal Error When Using mex -setup (PC). Some antivirus software packages such
as Cheyenne AntiVirus and Dr. Solomon may conflict with the mex -setup
process. If you get an error message during mex -setup of the following form
mex.bat: internal error in sub get_compiler_info(): don't
recognize <string>
then you need to disable your antivirus software temporarily and rerun
mex -setup. After you have successfully run the setup option, you can
re-enable your antivirus software.
2-27
2 Installation and Configuration
Licensing Problem. If you do not have a valid license for the MATLAB Compiler,
you will get an error message similar to the following when you try to access
the Compiler.
Error: Could not check out a Compiler License:
No such feature exists.
MATLAB Compiler Does Not Generate MEX-File. If you experience other problems
with the MATLAB Compiler, contact Technical Support at The MathWorks at
[email protected].
2-28
3
Getting Started
with MEX-Files
A Simple Example - The Sierpinski Gasket . . . . . . 3-3
Invoking the M-File . . . . . . . . . . . . . . . . . 3-4
Compiling the M-File into a MEX-File . . . . . . . . . . 3-5
Invoking the MEX-File . . . . . . . . . . . . . . . . 3-5
This chapter gets you started compiling M-files with the MATLAB Compiler.
By the end of this chapter, you should know how to:
This chapter also lists the limitations and restrictions of the MATLAB
Compiler.
3-2
A Simple Example - The Sierpinski Gasket
theImage = zeros(1000,1000);
for i=1:numPoints
startPoint = floor((corners(theRand(i),:)+startPoint)/2);
theImage(startPoint(1),startPoint(2)) = 1;
end
3-3
3 Getting Started with MEX-Files
• Start with a triangle and from it remove a triangle that is one-half the height
of the original and inverted. This leaves three triangles.
• From each of the remaining three triangles, remove a triangle that is
one-fourth the height of these new triangles and inverted. This leaves nine
triangles.
• The process continues and at infinity the surface area becomes zero and the
length of the curve is infinite.
On the Pentium Pro 200, the M-file took about 10 seconds of CPU time to
calculate the first 50,000 points on the Sierpinski Gasket.
3-4
A Simple Example - The Sierpinski Gasket
Note The timings listed in this book were recorded on a Pentium Pro 200
MHz PC running Microsoft Windows NT. In each case, the code was executed
two times and the results of the second execution were captured for this book.
All of the timings listed throughout this book are for reference purposes only.
They are not absolute; if you execute the same example under the same
conditions, your times will probably differ from these values. Use these values
as a frame of reference only.
3-5
3 Getting Started with MEX-Files
MATLAB runs the MEX-file version (gasket.mex) rather than the M-file
version (gasket.m). Given an M-file and a MEX-file with the same root name
(gasket) in the same directory, the MEX-file takes precedence.
This produces
elapsed_time =
5.2880
The MEX-file runs about 33% faster than the M-file version.
3-6
Compiler Options and Macros
Note Macro options are intended to simplify the more common compilation
tasks. You can always use individual options to customize the compilation
process to satisfy your particular needs.
For detailed information about the macros included with the MATLAB
Compiler, as well complete information on all the other available Compiler
options, see the mcc reference page.
3-7
3 Getting Started with MEX-Files
For more information about Simulink in general, see Using Simulink. For more
information about Simulink S-functions, see Writing S-Functions.
Simulink-Specific Options
By using Simulink-specific options with the MATLAB Compiler, you can
generate an S-function that is compatible with the S-Function block. The
Simulink-specific options are -S, -u, and -y. Using any of these options with
the MATLAB Compiler causes it to generate code that is compatible with
Simulink.
3-8
Generating Simulink S-Functions
In the above line, the S-function will be generated with an input vector whose
width is 1 and an output vector whose with is 2. If you were to connect the
referencing S-function block to signals that do not correspond to the correct
number of inputs or outputs, Simulink will generate an error when the
simulation starts.
Note The MATLAB Compiler -S option does not support the passing of
parameters that is normally available with Simulink S-functions.
3-9
3 Getting Started with MEX-Files
Data Type
The input and output vectors for the Simulink S-function must be
double-precision vectors or scalars. You must ensure that the variables you use
in the M-code for input and output are also double-precision values.
Note Simulink S-functions that are generated via the -S option of the
Compiler are not currently compatible with Real-Time Workshop®. They can,
however, be used to rapidly prototype code in Simulink.
3-10
Converting Script M-Files to Function M-Files
• Function M-files
• Script M-files
• You can pass arguments to function M-files but not to script M-files.
• Variables used inside function M-files are local to that function; you cannot
access these variables from the MATLAB interpreter’s workspace unless
they are passed back by the function. By contrast, variables used inside
script M-files are shared with the caller’s workspace; you can access these
variables from the MATLAB interpreter command line.
The MATLAB Compiler cannot compile script M-files nor can it compile a
function M-file that calls a script.
Converting a script into a function is usually fairly simple. To convert a script
to a function, simply add a function line at the top of the M-file.
For example, consider the script M-file houdini.m.
m = magic(4); % Assign 4x4 matrix to m.
t = m .^ 3; % Cube each element of m.
disp(t); % Display the value of t.
Running this script M-file from a MATLAB session creates variables m and t in
your MATLAB workspace.
The MATLAB Compiler cannot compile houdini.m because houdini.m is a
script. Convert this script M-file into a function M-file by simply adding a
function header line.
function [m,t] = houdini(sz)
m = magic(sz); % Assign matrix to m.
t = m .^ 3; % Cube each element of m.
disp(t) % Display the value of t.
The MATLAB Compiler can now compile houdini.m. However, because this
makes houdini a function, running houdini.mex no longer creates variable m
3-11
3 Getting Started with MEX-Files
3-12
4
Stand-Alone
Applications
Differences Between MEX-Files
and Stand-Alone Applications . . . . . . . . . . 4-3
Troubleshooting . . . . . . . . . . . . . . . . . . 4-28
This chapter explains how to use the MATLAB Compiler to code and build
stand-alone applications. The first part of the chapter concentrates on using
the mbuild script to build stand-alone applications and the second part
concentrates on the coding of the applications. Stand-alone applications run
without the help of the MATLAB interpreter. In fact, stand-alone applications
run even if MATLAB is not installed on the system. However, stand-alone
applications do require the run-time shared libraries. The specific shared
libraries required for each platform are listed within the following sections.
Note You must have the optional MATLAB C/C++ Math Library installed on
your system if you want to create stand-alone applications. If your application
uses Handle Graphics, you must have the optional MATLAB C/C++ Graphics
Library installed on your system.
4-2
Differences Between MEX-Files and Stand-Alone Applications
• MEX-files run in the same process space as the MATLAB interpreter. When
you invoke a MEX-file, the MATLAB interpreter dynamically links in the
MEX-file.
• Stand-alone C or C++ applications run independently of MATLAB.
MEX-Files
It is now possible to call MEX-files from Compiler-generated stand-alone
applications. The Compiler will compile MEX-files whenever they are specified
on the command line or are located using the -h option to find helper functions.
The MEX-files will then be loaded and called by the stand-alone code.
If an M-file and a MEX-file appear in the same directory and the M-file
contains at least one function, the Compiler will compile the M-file instead of
the MEX-file. If the MEX-file is desired instead, you must use the %#mex
pragma. For more information on this pragma, see “%#mex” in Chapter 7.
Stand-Alone C Applications
To build stand-alone C applications as described in this chapter, MATLAB, the
MATLAB Compiler, a C compiler, and the MATLAB C/C++ Math Library must
be installed on your system.
The source code for a stand-alone C application consists either entirely of
M-files or some combination of M-files, MEX-files, and C or C++ source code
files.
4-3
4 Stand-Alone Applications
The MATLAB Compiler translates input M-files into C source code suitable for
your own stand-alone applications. After compiling this C source code, the
resulting object file is linked with the object libraries.
For more information about which libraries must be included when you
distribute a C application, see “Distributing Stand-Alone UNIX Applications”
on page 4-14 or “Distributing Stand-Alone Windows Applications” on page
4-26.
Note On the PC, the MATLAB C++ Math Library is static because the
different PC compiler vendors use different C++ name mangling algorithms.
4-4
Building Stand-Alone C/C++ Applications
Note This chapter assumes that you have installed and configured the
MATLAB Compiler.
Overview
On both operating systems, the steps you use to build stand-alone C and C++
applications are:
2 Verify that the MATLAB Compiler can link object files with the proper
libraries to form a stand-alone application.
4-5
4 Stand-Alone Applications
This figure shows the sequence on both platforms. The sections following the
flowchart provide more specific details for the individual platforms.
Start
2
1
Stop
2
4-6
Building Stand-Alone C/C++ Applications
Getting Started
Introducing mbuild
The MathWorks utility, mbuild, lets you customize the configuration and build
process. The mbuild script provides an easy way for you to specify an options
file that lets you:
Note If you are developing C++ applications, make sure your C++ compiler
supports the templates features of the C++ language. If it does not, you may
be unable to use the MATLAB C/C++ Math Library.
4-7
4 Stand-Alone Applications
Language Extension(s)
C .c
C++ .cpp
.C
.cxx
.cc
Note You can override the language choice that is determined from the
extension by using the -lang option of mbuild. For more information about
this option, as well as all of the other mbuild options, see the mbuild reference
page.
4-8
Building Stand-Alone Applications on UNIX
Preparing to Compile
This simple method works for the majority of users. Assuming filename.c
contains a main function, this example uses the system’s compiler as your
default compiler for creating your stand-alone application. If you are a user
who does not need to change C or C++ compilers, or you do not need to modify
your compiler options files, you can skip ahead in this section to “Verifying
mbuild” on page 4-12. If you need to know how to change the options file or
select a different compiler, continue with this section.
Changing Compilers
Changing the Default Compiler. You need to use the setup option if you want to
change any options or link against different libraries. At the UNIX prompt type
mbuild -setup
4-9
4 Stand-Alone Applications
The setup option creates a user-specific options file for your ANSI C or C++
compiler. Executing mbuild -setup presents a list of options files currently
included in the bin subdirectory of MATLAB.
mbuild -setup
Options files control which compiler to use, the compiler and link
command options, and the runtime libraries to link against.
To override the default options file, use the 'mbuild -f' command
(see 'mbuild -help' for more information).
1: /matlab/bin/mbuildopts.sh :
Build and link with MATLAB C/C++ Math Library
2: /matlab/bin/mbuildsglopts.sh :
Build and link with MATLAB C/C++ Graphics Library
Enter the number of the options file to use as your default options
file:
If there is more than one options file, you can select the one you want by
entering its number and pressing Return. If there is only one options file
available, it is automatically copied to your MATLAB directory if you do not
already have an mbuild options file. If you already have an mbuild options file,
you are prompted to overwrite the existing one.
Note The options file is stored in the .matlab/R12 subdirectory of your home
directory. This allows each user to have a separate mbuild configuration.
Using the setup option sets your default compiler so that the new compiler is
used everytime you use the mbuild script.
4-10
Building Stand-Alone Applications on UNIX
Modifying the Options File. Another use of the setup option is if you want to
change your options file settings. For example, if you want to make a change to
the current linker settings, or you want to disable a particular set of warnings,
you should use the setup option.
If you need to change the options that mbuild passes to your compiler or linker,
you must first run
mbuild -setup
which copies a master options file to your local MATLAB directory, typically
$HOME/.matlab/R12/mbuildopts.sh.
If you need to see which options mbuild passes to your compiler and linker, use
the verbose option, -v, as in
mbuild -v filename1 [filename2 …]
to generate a list of all the current compiler settings. To change the options, use
an editor to make changes to your options file, which is in your local matlab
directory. Your local matlab directory is a user-specific, MATLAB directory in
your individual home directory that is used specifically for your individual
options files. You can also embed the settings obtained from the verbose option
of mbuild into an integrated development environment (IDE) or makefile that
you need to maintain outside of MATLAB. Often, however, it is easier to call
mbuild from your makefile. See your system documentation for information on
writing makefiles.
Note Any changes made to the local options file will be overwritten if you
execute mbuild -setup. To make the changes persist through repeated uses of
mbuild -setup, you must edit the master file itself,
<matlab>/bin/mbuildopts.sh.
The -f option tells the mbuild script to use the options file, <file>. If <file>
is not in the current directory, then <file> must be the full pathname to the
desired options file. Using the -f option tells the mbuild script to use the
4-11
4 Stand-Alone Applications
specified options file for the current execution of mbuild only; it does not reset
the default compiler.
Verifying mbuild
There is C source code for an example ex1.c included in the <matlab>/extern/
examples/cmath directory, where <matlab> represents the top-level directory
where MATLAB is installed on your system. To verify that mbuild is properly
configured on your system to create stand-alone applications, copy ex1.c to
your local directory and type cd to change to that directory. Then, at the
MATLAB prompt, enter
mbuild ex1.c
This creates the file called ex1. Stand-alone applications created on UNIX
systems do not have any extensions.
Architecture Command
where:
<matlab> is the MATLAB root directory
<arch> is your architecture (i.e., alpha, hp700, hpux, lnx86, sgi, sgi64, or sol2)
4-12
Building Stand-Alone Applications on UNIX
1 3 5
2 4 6
ans =
4-13
4 Stand-Alone Applications
typically by typing its name at the UNIX prompt. The application should run
and display the message
Hello, World
When you execute the mcc command to link files and libraries, mcc actually
calls the mbuild script to perform the functions.
Note There is no support for the MATLAB C/C++ Graphics Library on the
IBM_RS platform.
4-14
Building Stand-Alone Applications on UNIX
4-15
4 Stand-Alone Applications
Language Extension(s)
C .c
C++ .cpp
.cxx
.cc
• If you include both C and C++ files, mbuild uses the C++ compiler and the
MATLAB C++ Math Library.
• If mbuild cannot deduce from the file extensions whether to compile in C or
C++, mbuild invokes the C compiler.
4-16
Building Stand-Alone Applications on PCs
Note You can override the language choice that is determined from the
extension by using the -lang option of mbuild. For more information about
this option, as well as all of the other mbuild options, see the mbuild reference
page.
mbuild uses the first occurrence of the options file it finds. If no options file is
found, mbuild searches your machine for a supported C compiler and uses the
factory default options file for that compiler. If multiple compilers are found,
you are prompted to select one.
Preparing to Compile
Note Refer to “Supported ANSI C and C++ PC Compilers” on page 2-15 for
information about supported compilers and important limitations. Watcom
10.6 and 11 are not supported for building stand-alone applications.
Choosing a Compiler
Systems with Exactly One C/C++ Compiler. If the MATLAB Compiler and your
supported C or C++ compiler are installed on your system, you are ready to
create C or C++ stand-alone applications. On systems where there is exactly
one C or C++ compiler available to you, the mbuild utility automatically
configures itself for the appropriate compiler. So, for many users, to create a C
or C++ stand-alone applications, you can simply enter
mbuild filename.c
4-17
4 Stand-Alone Applications
This simple method works for the majority of users. Assuming filename.c
contains a main function, this example uses your installed C or C++ compiler
as your default compiler for creating your stand-alone application. If you are a
user who does not need to change compilers, or you do not need to modify your
compiler options files, you can skip ahead in this section to “Verifying mbuild”
on page 4-22. If you need to know how to change the options file or select a
different compiler, continue with this section.
Note On Windows 95 and Windows 98 systems, if you get the error, out of
environment space, see “Out of Environment Space Running mex or mbuild”
on page 4-28 for more information.
Systems with More than One C/C++ Compiler. On systems where there is more than
one C or C++ compiler, the mbuild utility lets you select which of the compilers
you want to use. Once you choose your C or C++ compiler, that compiler
becomes your default compiler and you no longer have to select one when you
compile your stand-alone applications.
For example, if your system has both the Lcc and Microsoft Visual C/C++
compilers, when you enter for the first time
mbuild filename.c
Select a compiler:
[1] Lcc C version 2.4 in D:Applications\Mathworks\sys\lcc
[2] Microsoft Visual C/C++ version 6.0 in
D:\Applications\Microsoft Visual Studio
[0] None
Compiler:
Select the desired compiler by entering its number and pressing Return. You
are then asked to verify your information.
4-18
Building Stand-Alone Applications on PCs
Changing Compilers
Changing the Default Compiler. To change your default C or C++ compiler, you
select a different options file. You can do this at anytime by using the setup
command.
This example shows the process of changing your default compiler to the
Microsoft Visual C/C++ Version 6.0 compiler.
mbuild -setup
Select a compiler:
[1] Borland C++Builder version 5.0
[2] Borland C++Builder version 4.0
[3] Borland C++Builder version 3.0
[4] Borland C/C++ version 5.02
[5] Borland C/C++ version 5.0
[6] Borland C/C++ (free command line tools) version 5.5
[7] Lcc C version 2.4
[8] Microsoft Visual C/C++ version 6.0
[9] Microsoft Visual C/C++ version 5.0
[10] Microsoft Visual C/C++ version 4.2
[0] None
Compiler: 8
4-19
4 Stand-Alone Applications
Updated ...
If the specified compiler cannot be located, you are given the message:
The default location for <compiler-name> is <directory-name>,
but that directory does not exist on this machine.
Using the setup option sets your default compiler so that the new compiler is
used everytime you use the mbuild script.
Modifying the Options File. Another use of the setup option is if you want to
change your options file settings. For example, if you want to make a change to
the current linker settings, or you want to disable a particular set of warnings,
you should use the setup option.
The setup option copies the appropriate options file to your user profile
directory. To make your user-specific changes to the options file, you edit your
copy of the options file in your user profile directory to correspond to your
specific needs and save the modified file. This sets your default compiler’s
options file to your specific version. Table 4-3, Compiler Options Files on the
PC, lists the names of the PC options files included in this release of MATLAB.
If you need to see which options mbuild passes to your compiler and linker, use
the verbose option, -v, as in
mbuild -v filename1 [filename2 …]
to generate a list of all the current compiler settings used by mbuild. To change
the options, use an editor to make changes to your options file that corresponds
to your compiler. You can also embed the settings obtained from the verbose
4-20
Building Stand-Alone Applications on PCs
Note Any changes that you make to the local options file compopts.bat will
be overwritten the next time you run mbuild -setup. If you want to make
your edits persist through repeated uses of mbuild -setup, you must edit the
master file itself. The master options files are also located in <matlab>\bin.
Combining Customized C and C++ Options Files. The options files for mbuild have
changed as of MATLAB 5.3 (Release 11) so that the same options file can be
used to create both C and C++ stand-alone applications. If you have modified
your own separate options files to create C and C++ applications, you can
combine them into one options file.
To combine your existing options files into one universal C and C++ options file:
1 Copy from the C++ options file to the C options file all lines that set the
variables COMPFLAGS, OPTIMFLAGS, DEBUGFLAGS, and LINKFLAGS.
4-21
4 Stand-Alone Applications
2 In the C options file, within just those copied lines from step 1, replace all
occurrences of:
- COMPFLAGS with CPPCOMPFLAGS
- OPTIMFLAGS with CPPOPTIMFLAGS
- DEBUGFLAGS with CPPDEBUGFLAGS
- LINKFLAGS with CPPLINKFLAGS.
This process modifies your C options file to be a universal C/C++ options file.
The -f option tells the mbuild script to use the options file, <file>. If <file>
is not in the current directory, then <file> must be the full pathname to the
desired options file. Using the -f option tells the mbuild script to use the
specified options file for the current execution of mbuild only; it does not reset
the default compiler.
Verifying mbuild
There is C source code for an example, ex1.c, included in the
<matlab>\extern\examples\cmath directory, where <matlab> represents the
top-level directory where MATLAB is installed on your system. To verify that
mbuild is properly configured on your system to create stand-alone
applications, enter at the MATLAB prompt
mbuild ex1.c
Shared Libraries
All the libraries (WIN32 Dynamic Link Libraries, or DLLs) for MATLAB, the
MATLAB Compiler, and the MATLAB Math Library are in the directory
<matlab>\bin\win32
The .DEF files for the Microsoft and Borland compilers are in the
<matlab>\extern\include directory. All of the relevant libraries for building
4-22
Building Stand-Alone Applications on PCs
1 3 5
2 4 6
ans =
4-23
4 Stand-Alone Applications
Using an IDE
The MathWorks provides a MATLAB add-in for the Visual Studio development
system that lets you work easily within Microsoft Visual C/C++ (MSVC). The
MATLAB add-in for Visual Studio greatly simplifies using M-files in the MSVC
environment. The add-in automates the integration of M-files into Visual C++
projects. It is fully integrated with the MSVC environment.
The add-in for Visual Studio is automatically installed on your system when
you run either mbuild -setup or mex -setup and select Microsoft Visual C/C++
version 5 or 6. However, there are several steps you must follow in order to use
the add-in:
1 To build MEX-files with the add-in for Visual Studio, run the following
command at the MATLAB command prompt.
mex -setup
Follow the menus and choose either Microsoft Visual C/C++ 5.0 or 6.0. This
configures mex to use the selected Microsoft compiler and also installs the
necessary add-in files in your Microsoft Visual C/C++ directories.
Follow the menus and choose either Microsoft Visual C/C++ 5.0 or 6.0. This
configures mbuild to use the selected Microsoft compiler and also installs the
necessary add-in files into your Microsoft Visual C/C++ directories. (It is not
a problem if these overlap with the files installed by the mex -setup
command.)
4-24
Building Stand-Alone Applications on PCs
3 For either mex or stand-alone support, you should also run the following
commands at the MATLAB prompt.
cd(prefdir); mccsavepath;
These commands save your current MATLAB path to a file named mccpath
in your user preferences directory. (Type prefdir to see the name of your
user preferences directory.)
This step is necessary because the MATLAB add-in for Visual Studio runs
outside of the MATLAB environment, so it would have no way to determine
your MATLAB path. If you add directories to your MATLAB path and want
them to be visible to the MATLAB add-in, rerun the cd and mccsavepath
commands shown in this step and replace prefdir with the desired
pathname.
4 To configure the MATLAB add-in for Visual Studio to work with Microsoft
Visual C/C++:
a Select Tools -> Customize from the MSVC menu.
c Check MATLAB for Visual Studio on the Add-ins and Macro Files list
and click Close. The floating MATLAB add-in for Visual Studio toolbar
appears. The checkmark directs MSVC to automatically load the add-in
when you start MSVC again.
shell=c:\command.com /e:32768 /p
Help Icon
4-25
4 Stand-Alone Applications
4-26
Building Shared Libraries
and file1.c as
int times2(int x)
{
return 2 * x;
}
int times3(int x)
{
return 3 * x;
}
The command
mbuild file1.c file1.exports
4-27
4 Stand-Alone Applications
Troubleshooting
Troubleshooting mbuild
This section identifies some of the more common problems that might occur
when configuring mbuild to create stand-alone applications.
Options File Not Writeable. When you run mbuild -setup, mbuild makes a copy of
the appropriate options file and writes some information to it. If the options file
is not writeable, you are asked if you want to overwrite the existing options file.
If you choose to do so, the existing options file is copied to a new location and a
new options file is created.
mbuild Generates Errors. On UNIX, if you run mbuild filename and get errors, it
may be because you are not using the proper options file. Run mbuild -setup
to ensure proper compiler and linker settings.
Compiler and/or Linker Not Found. On PCs running Windows, if you get errors
such as unrecognized command or file not found, make sure the command
line tools are installed and the path and other environment variables are set
correctly in the options file.
mbuild Works from Shell but Not from MATLAB (UNIX). If the command
mbuild ex1.c
works from the UNIX command prompt but does not work from the MATLAB
prompt, you may have a problem with your .cshrc file. When MATLAB
4-28
Troubleshooting
prior to launching MATLAB. If this works correctly, then you should check
your .cshrc file for problems setting the PATH environment variable.
Cannot Locate Your Compiler (PC). If mbuild has difficulty locating your installed
compilers, it is useful to know how it goes about finding compilers. mbuild
automatically detects your installed compilers by first searching for locations
specified in the following environment variables:
Internal Error When Using mbuild -setup (PC). Some antivirus software packages
such as Cheyenne AntiVirus and Dr. Solomon may conflict with the mbuild
-setup process. If you get an error message during mbuild -setup of the
following form
mex.bat: internal error in sub get_compiler_info(): don't
recognize <string>
then you need to disable your antivirus software temporarily and rerun
mbuild -setup. After you have successfully run the setup option, you can
re-enable your antivirus software.
4-29
4 Stand-Alone Applications
Licensing Problem. If you do not have a valid license for the MATLAB Compiler,
you will get an error message similar to the following when you try to access
the Compiler.
Error: Could not check out a Compiler License:
No such feature exists.
MATLAB Compiler Does Not Generate Application. If you experience other problems
with the MATLAB Compiler, contact Technical Support at The MathWorks at
[email protected].
4-30
Coding with M-Files Only
Note It is good practice to avoid manually modifying the C or C++ code that
the MATLAB Compiler generates. If the generated C or C++ code is not to
your liking, modify the M-file (and/or the compiler options) and then
recompile. If you do edit the generated C or C++ code, remember that your
changes will be erased the next time you recompile the M-file. For more
information, see “Compiling MATLAB Provided M-Files Separately” on page
4-35 and “Interfacing M-Code to C/C++ Code” in Chapter 5.
Consider a very simple application whose source code consists of two M-files,
mrank.m and main.m. This example involves C code; you use a similar process
(described below) for C++ code. In this example, the line r = zeros(n,1)
preallocates memory to help the performance of the Compiler.
mrank.m returns a vector of integers, r. Each element of r represents the rank
of a magic square. For example, after the function completes, r(3) contains the
rank of a 3-by-3 magic square.
function r = mrank(n)
r = zeros(n,1);
for k = 1:n
r(k) = rank(magic(k));
end
main.m contains a “main routine” that calls mrank and then prints the results
function main
r = mrank(5)
To compile these into code that can be built into a stand-alone application,
invoke the MATLAB Compiler.
mcc -mc main mrank
4-31
4 Stand-Alone Applications
The -m option flag causes the MATLAB Compiler to generate C source code
suitable for stand-alone applications. For example, the MATLAB Compiler
generates C source code files main.c, main_main.c, and mrank.c. main_main.c
contains a C function named main; main.c and mrank.c contain a C functions
named mlfMain and mlfMrank. (The -c option flag inhibits invocation of
mbuild.)
To build an executable application, you can use mbuild to compile and link
these files. Or, you can automate the entire build process (invoke the MATLAB
Compiler twice, use mbuild to compile the files with your ANSI C compiler, and
link the code) by using the command
mcc -m main mrank
4-32
Coding with M-Files Only
main.m mrank.m
C Compiler C Compiler
4-33
4 Stand-Alone Applications
For C++ code, add -L cpp to the previous commands, use a C++ compiler
instead of a C compiler, and use the MATLAB C/C++ Math Library. See the
MATLAB C++ Math Library User’s Guide for details.
4-34
Alternative Ways of Compiling M-Files
Note These two alternative ways of compiling M-files apply to C++ as well as
to C code; the only difference is that you add -L cpp for C++.
Copy this code into a file named rank.m located in the same directory as
mrank.m and main.m. Then, modify your version of rank.m. After completing the
modifications, compile rank.m.
mcc -t rank
4-35
4 Stand-Alone Applications
To compile and link all four C source code files (main.c, rank.c, mrank.c, and
main_main.c) into a stand-alone application, use
mcc -m main_main.c main.c rank.c mrank.c
For C++
mcc -p main rank
These commands create files containing the C or C++ source code. The macro
options -m and -p automatically compile all helper functions.
4-36
Mixing M-Files and C or C++
• The first example is a simple application that mixes M-files and C code.
• The second example illustrates how to write C code that calls a compiled
M-file.
Note If you include compiled M code into a larger application, you must
produce a library wrapper file even if you do not actually create a separate
library. For more information on creating libraries, see the library sections in
“Supported Executable Types” in Chapter 5.
Simple Example
This example involves mixing M-files and C code. Consider a simple
application whose source code consists of mrank.m and mrankp.c.
mrank.m
mrank.m contains a function that returns a vector of the ranks of the magic
squares from 1 to n.
function r = mrank(n)
r = zeros(n,1);
for k = 1:n
r(k) = rank(magic(k));
end
4-37
4 Stand-Alone Applications
The MATLAB Compiler generates C source code files named mrank.c, Pkg.c,
and Pkg.h. This command invokes mbuild to compile the resulting
Compiler-generated source files (mrank.c, Pkg.c, Pkg.h) with the existing C
source file (mrankp.c) and links against the required libraries. For details, see
“Building Stand-Alone C/C++ Applications” on page 4-5.
The MATLAB Compiler provides two different versions of mrankp.c in the
<matlab>/extern/examples/compiler directory:
4-38
Mixing M-Files and C or C++
mrank.m
mcc -t -W lib:Pkg -T
link:exe mrank mrankp.c
C Compiler C Compiler
4-39
4 Stand-Alone Applications
mrankp.c
The code in mrankp.c calls mrank and outputs the values that mrank returns.
/*
* MRANKP.C
* "Posix" C main program illustrating the use of the MATLAB Math
* Library.
* Calls mlfMrank, obtained by using MCC to compile mrank.m.
*
* $Revision: 1.3 $
*
*/
#include <stdio.h>
#include <math.h>
#include "matlab.h"
4-40
Mixing M-Files and C or C++
An Explanation of mrankp.c
The heart of mrankp.c is a call to the mlfMrank function. Most of what comes
before this call is code that creates an input argument to mlfMrank. Most of
what comes after this call is code that displays the vector that mlfMrank
returns. First, the code must call the Compiler-generated library initialization
function.
PkgInitialize();/* Initialize the library of M-Functions */
According to the function header, mlfMrank expects one input parameter and
returns one value. All input and output parameters are pointers to the mxArray
data type. (See “External Interfaces/API” for details on the mxArray data type.)
To create and manipulate mxArray * variables in your C code, you can call the
mx routines described in the “External Interfaces/API” or any routine in the
MATLAB C/C++ Math Library. For example, to create a 1-by-1 mxArray *
variable named N with real data, mrankp calls mlfScalar.
N = mlfScalar(n);
mrankp can now call mlfMrank, passing the initialized N as the sole input
argument.
R = mlfMrank(N);
4-41
4 Stand-Alone Applications
Advanced C Example
This section illustrates an advanced example of how to write C code that calls
a compiled M-file. Consider a stand-alone application whose source code
consists of two files:
multarg.m specifies two input parameters and returns two output parameters.
function [a,b] = multarg(x,y)
a = (x + y) * pi;
b = svd(svd(a));
The code in multargp.c calls mlfMultarg and then displays the two values that
mlfMultarg returns.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "matlab.h"
#include "multpkg.h"/* Include Compiler-generated header file */
4-42
Mixing M-Files and C or C++
4-43
4 Stand-Alone Applications
You can build this program into a stand-alone application by using the
command:
mcc -t -W lib:multpkg -T link:exe multarg multargp.c libmmfile.mlib
The program first displays the contents of a 3-by-3 matrix a and then displays
the contents of scalar b:
6.2832 +34.5575i 25.1327 +25.1327i 43.9823 +43.9823i
12.5664 +34.5575i 31.4159 +31.4159i 50.2655 +28.2743i
18.8496 +18.8496i 37.6991 +37.6991i 56.5487 +28.2743i
143.4164
This C function header shows two input arguments (mxArray *x and mxArray
*y) and two output arguments (the return value and mxArray **b).
Use mxCreateDoubleMatrix to create the two input matrices (x and y). Both x
and y contain real and imaginary components. The memcpy function initializes
the components, for example,
x = mxCreateDoubleMatrix(ROWS, COLS, COMPLEX);
memcpy(mxGetPr(x), x_pr, ROWS * COLS * sizeof(double));
memcpy(mxGetPi(y), y_pi, ROWS * COLS * sizeof(double));
The code in this example initializes variable x from two arrays (x_pr and x_pi)
of predefined constants. A more realistic example would read the array values
from a data file or a database.
After creating the input matrices, main calls mlfMultarg.
a = (mxArray *)mlfMultarg(&b, x, y);
4-44
Mixing M-Files and C or C++
The mlfMultarg function returns matrices a and b. a has both real and
imaginary components; b is a scalar having only a real component. The
program uses mlfPrintMatrix to output the matrices, for example,
mlfPrintMatrix(a);
4-45
4 Stand-Alone Applications
4-46
5
Controlling
Code Generation
Code Generation Overview . . . . . . . . . . . . . 5-3
This chapter describes the code generated by the MATLAB Compiler and the
options that you can use to control code generation. In particular, it discusses:
5-2
Code Generation Overview
theImage = zeros(1000,1000);
for i=1:numPoints
startPoint = floor((corners(theRand(i),:)+startPoint)/2);
theImage(startPoint(1),startPoint(2)) = 1;
end
5-3
5 Controlling Code Generation
foo M-File
function [a, b] = foo(x, y)
if nargout == 0
elseif nargout == 1
a = x;
elseif nargout == 2
a = x;
b = y;
end
fun M-File
function a = fun(b)
a(1) = b(1) .* b(1);
a(2) = b(1) + b(2);
a(3) = b(2) / 4;
sample M-File
function y = sample( varargin )
varargin{:}
y = 0;
Generated Code
This chapter investigates the generated header files, interface functions, and
wrapper functions for the C MEX, stand-alone C and C++ targets, and C and
C++ libraries.
When you use the MATLAB Compiler to compile an M-file, it generates these
files:
The C or C++ code that is generated by the Compiler and the header file are
independent of the final target type and target platform. That is, the C or C++
code and header file are identical no matter what the desired final output. The
wrapper file provides the code necessary to support the output executable type.
So, the wrapper file is different for each executable type.
5-4
Code Generation Overview
This table shows the names of the files generated when you compile a generic
M-file (file.m) for the MEX and stand-alone targets. The table also shows the
files generated when you compile a set of files (filelist) for the library target.
C C++
Note Many of the code snippets generated by the MATLAB Compiler that
are used in this chapter use the -F page-width option to produce readable
code that fits nicely on the book’s printed page. For more information about
the page-width option, see “Formatting Compiler-Generated Code” on page
5-29.
5-5
5 Controlling Code Generation
Note Although Compiler 2.1 can currently compile method functions, it does
not support overloading of methods as implemented in MATLAB. This feature
is provided in anticipation of support of overloaded methods being added.
Method directories can contain private directories. Private functions are found
only when executing a method from the parent method directory. Taking all of
this into account, the Compiler command line needs to be able to differentiate
between these various functions that have the same name. A file called foo.m
that contains a function called foo can appear in all of these locations at the
same time. The conventions used on the Compiler command line are as
documented in this table.
Name Description
5-6
Compiling Private and Method Functions
This table lists the functions you can specify on the command line and their
corresponding function and filenames.
For private functions, the name given in the table above may be ambiguous.
The MATLAB Compiler generates a warning when it cannot distinguish which
private function to use. For example, given these two foo.m private functions
and their locations
/Z/X/private/foo.m
/Y/X/private/foo.m
the Compiler searches up only one level and determines the path to the file as
X/private/foo.m
Since it is ambiguous which foo.m you are requesting, it generates the warning
Warning: The specified private directory is not unique. Both
/Z/X/private and /Y/X/private are found on the path for this
private directory.
5-7
5 Controlling Code Generation
C Header File
If the target language is C, the Compiler generates the header file, gasket.h.
This example uses the Compiler command
mcc -t -L C -T codegen -F page-width:60 gasket
#ifndef MLF_V2
#define MLF_V2 1
#endif
#ifndef __gasket_h
#define __gasket_h 1
#ifdef __cplusplus
extern "C" {
#endif
#include "libmatlb.h"
5-8
The Generated Header Files
#ifdef __cplusplus
}
#endif
#endif
#include "matlab.hpp"
5-9
5 Controlling Code Generation
#endif
5-10
Internal Interface Functions
C Interface Functions
The C interface functions process any input arguments and pass them to the
implementation version of the function, Mf.
would use the feval interface. The following C code is the corresponding feval
interface (mlxGasket) from the Sierpinski Gasket example. This function calls
the C Mgasket function.
/*
* The function "mlxGasket" contains the feval interface
* for the "gasket" M-function from file
* "<matlab>\extern\examples\compiler\gasket.m" (lines 1-23).
* The feval function calls the implementation version of
* gasket through this function. This function processes
* any input arguments and passes them to the
* implementation version of the function, appearing above.
*/
void mlxGasket(int nlhs,
mxArray * plhs[],
int nrhs,
mxArray * prhs[]) {
5-11
5 Controlling Code Generation
mxArray * mprhs[1];
mxArray * mplhs[1];
int i;
if (nlhs > 1) {
mlfError(_mxarray0_);
}
if (nrhs > 1) {
mlfError(_mxarray2_);
}
for (i = 0; i < 1; ++i) {
Input argument mplhs[i] = mclGetUninitializedArray();
processing }
for (i = 0; i < 1 && i < nrhs; ++i) {
mprhs[i] = prhs[i];
}
for (; i < 1; ++i) {
mprhs[i] = NULL;
Call to C }
implementation mlfEnterNewContext(0, 1, mprhs[0]);
function mplhs[0] = Mgasket(nlhs, mprhs[0]);
Output argument mlfRestorePreviousContext(0, 1, mprhs[0]);
processing plhs[0] = mplhs[0];
}
5-12
Internal Interface Functions
/*
* The function "mlfGasket" contains the normal interface
* for the "gasket" M-function from file
* "<matlab>\extern\examples\compiler\gasket.m" (lines 1-23).
* This function processes any input arguments and passes
* them to the implementation version of the function,
* appearing above.
*/
mxArray * mlfGasket(mxArray * numPoints) {
int nargout = 1;
Input argument mxArray * theImage = mclGetUninitializedArray();
processing
mlfEnterNewContext(0, 1, numPoints);
Call M-function theImage = Mgasket(nargout, numPoints);
Output argument mlfRestorePreviousContext(0, 1, numPoints);
processing return mlfReturnValue(theImage);
}
5-13
5 Controlling Code Generation
5-14
Internal Interface Functions
Note In C++, the mlxF interface functions are also C functions in order to
allow the feval interface to be uniform between C and C++.
5-15
5 Controlling Code Generation
would use the feval interface. The following C++ code is the corresponding
feval interface (mlxGasket) from the Sierpinski Gasket example. This function
calls the C++ Mgasket function.
//
// The function "mlxGasket" contains the feval interface
// for the "gasket" M-function from file
// "<matlab>\extern\examples\compiler\gasket.m" (lines 1-23).
// The feval function calls the implementation version of
// gasket through this function. This function processes
// any input arguments and passes them to the
// implementation version of the function, appearing above.
//
void mlxGasket(int nlhs,
mxArray * plhs[],
int nrhs,
mxArray * prhs[]) {
MW_BEGIN_MLX();
{
mwArray mprhs[1];
mwArray mplhs[1];
int i;
mclCppUninitializeArrays(1, mplhs);
if (nlhs > 1) {
error(_mxarray0_);
}
Input argument if (nrhs > 1) {
processing error(_mxarray2_);
}
for (i = 0; i < 1 && i < nrhs; ++i) {
mprhs[i] = mwArray(prhs[i], 0);
}
for (; i < 1; ++i) {
mprhs[i].MakeDIN();
}
Call M-function mplhs[0] = Mgasket(nlhs, mprhs[0]);
Output argument plhs[0] = mplhs[0].FreezeData();
processing }
MW_END_MLX();
}
5-16
Internal Interface Functions
F Interface Function
The Compiler always generates the F interface function, which contains the
“normal” C++ interface to the function. This code is the corresponding C++
interface function (gasket) from the Sierpinski Gasket example. This function
calls the C++ code.
//
// The function "gasket" contains the normal interface for
// the "gasket" M-function from file
// "<matlab>\extern\examples\compiler\gasket.m" (lines 1-23).
// This function processes any input arguments and passes
// them to the implementation version of the function,
// appearing above.
//
mwArray gasket(mwArray numPoints) {
int nargout(1);
mwArray theImage(mclGetUninitializedArray());
Call M-function theImage = Mgasket(nargout, numPoints);
Output argument return theImage;
processing }
N F Interface Function
The Compiler produces this interface function only when the M-function uses
the variable nargout. The nargout interface allows the number of requested
outputs to be specified via the nargout argument, as opposed to the normal
interface that dynamically calculates the number of outputs based on the
number of non-null inputs it receives.
This is the corresponding NF interface function (NFoo) for the foo.m example
described earlier in this chapter. This function calls the Mfoo function
appearing in foo.cpp.
//
// The function "Nfoo" contains the nargout interface for
// the "foo" M-function from file
// "<matlab>\extern\examples\compiler\foo.m" (lines 1-8).
// This interface is only produced if the M-function uses
// the special variable "nargout". The nargout interface
// allows the number of requested outputs to be specified
// via the nargout argument, as opposed to the normal
5-17
5 Controlling Code Generation
VF Interface Function
The Compiler produces this interface function only when the M-function uses
the variable nargout and has at least one output. The void interface function
specifies zero output arguments to the implementation version of the function,
and in the event that the implementation version still returns an output
(which, in MATLAB, would be assigned to the ans variable), it deallocates the
output.
This is the corresponding VF interface function (VFoo) for the foo.m example
described earlier in this chapter. This function calls the Mfoo function
appearing in foo.cpp.
//
// The function "Vfoo" contains the void interface for the
// "foo" M-function from file
// "<matlab>\extern\examples\compiler\foo.m" (lines 1-8).
// The void interface is only produced if the M-function
// uses the special variable "nargout", and has at least
// one output. The void interface function specifies zero
// output arguments to the implementation version of the
// function, and in the event that the implementation
5-18
Internal Interface Functions
5-19
5 Controlling Code Generation
This section discusses the various wrappers that can be generated using the
MATLAB Compiler.
Note When the Compiler generates a wrapper function, it must examine all
of the .m files that will be included into the executable. If you do not include all
the files, the Compiler may not define all of the global variables. Optimized
code will not run at all without initialization.
Generating Files
You can use the -t option of the Compiler to generate source files in addition
to wrapper files. For example,
mcc -W main -h x.m
examines x.m and all M-files referenced by x.m, but generates only the
x_main.c wrapper file. However, including the -t option in
mcc -W main -h -t x.m
5-20
Supported Executable Types
MEX-Files
The -W mex -L C options produce the MEX-file wrapper, which includes the
mexFunction interface that is standard to all MATLAB plug-ins. For more
information about the requirements of the mex interface, see “External
Interfaces/API.”
In addition to declaring globals and initializing the feval function table, the
MEX-file wrapper function includes interface and definition functions for all
M-files not included into the set of compiled files. These functions are
implemented as callbacks to MATLAB.
Note By default, the -x option does not include any functions that do not
appear on the command line. Functions that do not appear on the command
line would generate a callback to MATLAB. Specify -h if you want all
functions called to be compiled into your MEX-file.
Main Files
You can generate C or C++ application wrappers that are suitable for building
C or C++ stand-alone applications, respectively. These POSIX-compliant main
wrappers accept strings from the POSIX shell and return a status code. They
are meant to translate “command-like” M-files into POSIX main applications.
If you write a function that accepts strings in MATLAB, that function will
compile to a POSIX main wrapper in such a way that it behaves the same from
the DOS/UNIX command line as it does from within MATLAB.
5-21
5 Controlling Code Generation
The Compiler processes the string arguments passed to the main() function
and sends them into the compiled M-function as strings.
For example, consider this M-file, sample.m.
function y = sample( varargin )
varargin{:}
y = 0;
You can compile sample.m into a POSIX main application. If you call sample
from MATLAB, you get
sample hello world
ans =
hello
ans =
world
ans =
0
If you compile sample.m and call it from the DOS shell, you get
C:\> sample hello world
ans =
hello
ans =
world
C:\>
5-22
Supported Executable Types
Simulink S-Functions
The -W simulink -L C options produce a Simulink S-function wrapper.
Simulink S-function wrappers conform to the Simulink C S-function
conventions. The wrappers initialize:
Note By default, the -S command does not include any functions that do not
appear on the command line. Functions that do not appear on the command
line would generate a callback to MATLAB. Specify -h if you want all
functions called to be compiled into your MEX-file.
C Libraries
The intent of the C library wrapper files is to allow the inclusion of an arbitrary
set of M-files into a static library or shared library. The header file contains all
of the entry points for all of the compiled M functions. The export list contains
the set of symbols that are exported from a C shared library.
Another benefit of creating a library is that you can compile a common set of
functions once. You can then compile other M-functions that depend on them
without recompiling the original functions. You can accomplish this using mlib
files, which are automatically generated when you generate the library. For
more information about mlib files, see “mlib Files” on page 5-25.
Note Even if you are not producing a shared library, you must generate a
library wrapper file when including any Compiler-generated code into a larger
application.
5-23
5 Controlling Code Generation
File Description
libtimefun.c
The C wrapper file (libtimefun.c) contains the initialization
(libtimefunInitialize) and termination (libtimefunTerminate) functions
for the library. You must call libtimefunInitialize before you call any
Compiler-generated code. This function initializes the state of
Compiler-generated functions so that those functions can be called from C code
not generated by the Compiler. You must also call libtimefunTerminate before
you unload the library.
The library files in this example are produced from the command
mcc -W lib:libtimefun -L C weekday date tic calendar toc
C Shared Library
The MATLAB Compiler allows you to build a shared library from the files
created in the previous section, “C Libraries.” To build the shared library,
libtimefun.ext, in one step, use
mcc -W lib:libtimefun -L C -t -T link:lib -h weekday date tic calendar toc
The -t option tells the Compiler to generate C code from each of the listed
M-files. The -T link:lib option tells the Compiler to compile and link a shared
library. The -h option tells the Compiler to include any other M-functions
called from those listed on the mcc command line, i.e., helper functions.
5-24
Supported Executable Types
mlib Files
Shared libraries, like libraries, let you compile a common set of functions once
and then compile other M-functions that depend on them without compiling
them again.You accomplish this using mlib files, which are automatically
generated when you generate the shared library.
Creating an mlib File. When you create a library wrapper file, you also get a .mlib
file with the same base name. For example,
mcc -W lib:libtimefun -L C -t -T link:lib -h weekday date tic calendar toc
creates
libtimefun.c
libtimefun.h
libtimefun.exports
libtimefun.mlib
libtimefun.ext
The last file, libtimefun.ext, is the shared library file for your platform. For
example, on the PC, the shared library is
libtimefun.dll
Using an mlib File. This example uses two function, tic and toc, that are in the
shared library. Consider a new function, timer, defined as
function timer
tic
x = fft(1:1000);
toc
both tic and toc would be recompiled due to the implicit -h option included in
the -m macro. Using mlib files, you would use
mcc -m timer libtimefun.mlib
At compile time, function definitions for tic and toc are located in the
libtimefun.mlib file, indicating that all future references to tic and toc
should come from the mlib files’s corresponding shared library. When the
5-25
5 Controlling Code Generation
An advantage of using mlib files is that the generated code is smaller because
some of the code is now located in the shared library.
Note On the mcc command line, you can access any mlib file by including the
full path to the file. For example,
Restrictions.
C++ Libraries
The intent of the C++ library wrapper files is to allow the inclusion of an
arbitrary set of M-files into a library. The header file contains all of the entry
points for all of the compiled M functions.
Note Even if you are not producing a separate library, you must generate a
library wrapper file when including any Compiler-generated code into a larger
application.
5-26
Supported Executable Types
File Description
Note On some platforms, including Microsoft Windows NT, support for C++
shared libraries is limited and the C++ mangled function names must be
exported. Refer to your vendor-supplied documentation for details on creating
C++ shared libraries.
libtimefun.cpp
The C++ wrapper file (libtimefun.cpp) initializes the state of
Compiler-generated functions so that those functions can be called from C++
code not generated by the Compiler. These files are produced from the
command
mcc -W lib:libtimefun -L Cpp weekday date tic calendar toc
5-27
5 Controlling Code Generation
5-28
Formatting Compiler-Generated Code
The remaining sections focus on the different choices you can use.
Note When using -A line:on, which is the default with the MATLAB add-in
for Visual Studio, the page width is set as large as possible to support
source-level debugging and this setting is ignored.
Default Width
Not specifying a page width formatting option uses the default of 80. Using
mcc -x gasket
5-29
5 Controlling Code Generation
0 1 2 3 4 5 6 7 8
12345678901234567890123456789012345678901234567890123456789012345678901234567890
for (mclForStart(
&viter__, mlfScalar(1), mclVa(numPoints, "numPoints"), NULL);
mclForNext(&viter__, &i);
) {
/*
* startPoint = floor((corners(theRand(i),:)+startPoint)/2);
*/
mlfAssign(
&startPoint,
mlfFloor(
mclMrdivide(
mclPlus(
mclVe(
mlfIndexRef(
mclVsv(corners, "corners"),
"(?,?)",
mlfIndexRef(
mclVsv(theRand, "theRand"), "(?)", mclVsv(i, "i")),
mlfCreateColonIndex())),
mclVv(startPoint, "startPoint")),
mlfScalar(2))));
.
.
.
Page Width = 40
This example specifies a page width of 40.
mcc -x -F page-width:40 gasket
mlfAssign(
&theImage,
mlfZeros(
mlfScalar(1000),
mlfScalar(1000),
NULL));
/*
*
* corners = [866 1;1 500;866 1000];
*/
mlfAssign(
5-30
Formatting Compiler-Generated Code
&corners,
mlfDoubleMatrix(
3,
2,
_array0_,
(double *)NULL));
/*
* startPoint = [866 1];
*/
mlfAssign(
&startPoint,
mlfDoubleMatrix(
1,
2,
_array1_,
(double *)NULL));
/*
* theRand = rand(numPoints,1);
*/
mlfAssign(
&theRand,
mlfNRand(
1,
mclVa(numPoints, "numPoints"),
mlfScalar(1),
NULL));
/*
* theRand = ceil(theRand*3);
*/
mlfAssign(
&theRand,
mlfCeil(
mclMtimes(
mclVv(theRand, "theRand"),
mlfScalar(3))));
.
.
.
5-31
5 Controlling Code Generation
Default Indentation
Not specifying indent formatting options uses the default of four spaces for
statements and two spaces for expressions. For example, using
mcc -x gasket
5-32
Formatting Compiler-Generated Code
Modified Indentation
This example shows the same segment of code using a statement indentation
of two and an expression indentation of one.
mcc -F statement-indent:2 -F expression-indent:1 -x gasket
5-33
5 Controlling Code Generation
You can combine annotation options, for example selecting both comments and
#line directives. The remaining sections focus on the different choices you can
use.
Comments Annotation
To include only comments from the source M-file in the generated output, use
mcc -A annotation:comments …
This code snippet shows the generated code containing only the comments.
5-34
Including M-File Information in Compiler Output
All Annotation
To include both comments and source code from the source M-file in the
generated output, use
mcc -A annotation:all …
or do not stipulate the annotation option, thus using the default of all.
The code snippet contains both comments and source code.
5-35
5 Controlling Code Generation
No Annotation
To include no source from the initial M-file in the generated output, use
mcc -A annotation:none …
This code snippet shows the generated code without comments and source code.
static void Mhello(void) {
mxArray * ans = mclGetUninitializedArray();
mclAssignAns(
&ans,
mlfNFprintf(0, mlfScalar(1), mxCreateString("Hello, World\\n"), NULL));
mxDestroyArray(ans);
}
.
.
.
Note When using the #line directive, the page-width directive is disabled in
order to make the code work properly with the C debugger.
5-36
Including M-File Information in Compiler Output
The Hello, World example produces the following code segment when this
option is selected.
.
Line 1 #line 1 "<matlab>\\extern\\examples\\compiler\\hello.m"
static void Mhello(void) {
Line 1 #line 1 "<matlab>\\extern\\examples\\compiler\\hello.m"
mxArray * ans = mclGetUninitializedArray();
/*
* % This is the hello, world function written in M code
* % $Revision: 1.1 $
* %
* fprintf(1,'Hello, World\n' );
*/
Line 5 #line 5 "<matlab>\\extern\\examples\\compiler\\hello.m"
mclAssignAns(
Line 5 #line 5 "<matlab>\\extern\\examples\\compiler\\hello.m"
&ans,
Line 5 #line 5 "<matlab>\\extern\\examples\\compiler\\hello.m"
mlfNFprintf(0, mlfScalar(1), mxCreateString("Hello, World\\n"), NULL));
Line 5 #line 5 "<matlab>\\extern\\examples\\compiler\\hello.m"
mxDestroyArray(ans);
Line 5 #line 5 "<matlab>\\extern\\examples\\compiler\\hello.m"
}
.
.
.
In this example, Line 1 points to lines in the generated C code that were
produced by line 1 from the M-file, that is
function hello
Line 5 points to lines in the C code that were produced by line 5 of the M-file, or
fprintf(1,'Hello, World\n' );
5-37
5 Controlling Code Generation
y = mmult(a,b)
function y = mmult(a,b)
y = a*b;
The information about where the error occurred is not available. However, if
you compile tmmult.m and use the -A debugline:on option as in
mcc -x -A debugline:on tmmult
5-38
Including M-File Information in Compiler Output
tmmult
Inner matrix dimensions must agree.
Error in File: "<matlab>\extern\examples\compiler\tmmult.m",
File/line # Function: "tmmult", Line: 5.
Note When using the -A debugline:on option, the lasterr function returns
a string that includes the line number information. If, in your M-code, you
compare against the string value of lasterr, you will get different behavior
when using this option.
5-39
5 Controlling Code Generation
C Example
Suppose you have a C function that reads data from a measurement device. In
M-code, you want to simulate the device by providing a sine wave output. In
production, you want to provide a function that returns the measurement
obtained from the device. You have a C function called
measure_from_device() that returns a double, which is the current
measurement.
collect.m contains the M-code for the simulation of your application.
function collect
function y = collect_one
persistent t;
if (isempty(t))
t = 0;
end
t = t + 0.05;
y = sin(t);
5-40
Interfacing M-Code to C/C++ Code
private, or method). When using this pragma, the Compiler will generate an
additional header file called file_external.h or file_external.hpp, where
file is the name of the initial M-file containing the %#external pragma. This
header file will contain the extern declaration of the function that the user
must provide. This function must conform to the same interface as the
Compiler-generated code.
The Compiler will still generate a .c or .cpp file from the .m file in question.
The Compiler will generate the feval table, which includes the function and
all of the required interface functions for the M-function, but the body of
M-code from that function will be ignored. It will be replaced by the
hand-written code. The Compiler will generate the interface for any functions
that contain the %#external pragma into a separate file called
file_external.h or file_external.hpp. The Compiler-generated C or C++
file will include this header file to get the declaration of the function being
provided.
In this example, place the pragma in the collect_one local function.
function collect
function y = collect_one
%#external
persistent t;
if (isempty(t))
t = 0;
end
t = t + 0.05;
end
y = sin(t);
When this file is compiled, the Compiler creates the additional header file
collect_external.h, which contains the interface between the
Compiler-generated code and your code. In this example, it would contain
extern mxArray *Mcollect_collect_one( int nargout_ );
5-41
5 Controlling Code Generation
We recommend that you include this header file when defining the function.
This function could be implemented in this C file, measure.c, using the
measure_from_device() function.
#include "matlab.h"
#include "collect_external.h"
#include <math.h>
In general, the Compiler will use the same interface for this function as it
would generate. To generate the C code and header file, use
mcc -c collect.m
Using Pragmas
Using feval
In stand-alone C and C++ modes, the pragma
%#function <function_name-list>
informs the MATLAB Compiler that the specified function(s) will be called
through an feval call or through a MATLAB function that accepts a function
to feval as an argument or contains an eval string or Handle Graphics
5-42
Interfacing M-Code to C/C++ Code
callback that references the specified function. Without this pragma, the -h
option will not be able to locate and compile all M-files used in your application.
If you are using the %#function pragma to define functions that are not
available in M-code, you must write a dummy M-function that identifies the
number of input and output parameters to the M-file function with the same
name used on the %#function line. For example,
%#function myfunctionwritteninc
and includes the %#external pragma. This statement indicates that the
function takes three inputs (a, b, c) and returns a single output variable (y). No
other lines need to be present in the M-function.
Compiling MEX-Files
If the Compiler finds both a function M-file and a .mex file in the same
directory, it will assume that the .mex file is the compiled version of the M-file.
In those cases, if the M-file version is not desired, use the %#mex pragma to force
the Compiler to use the MEX-file. For example,
function y = gamma(x)
%#mex
error('gamma MEX-file is missing');
5-43
5 Controlling Code Generation
Print Handlers
A print handler is a routine that controls how your application displays the
output generated by calls to mlf routines.
The system provides a default print handler for your application. The default
print handler writes output to the standard output stream. If this print
handler is suitable for your application, you do not need to write and register
another print handler.
However, you can override the default behavior by writing and registering an
alternative print handler. In fact, if you are coding a stand-alone application
with a GUI, then you must register another print handler to display application
output inside a GUI mechanism, such as a Windows message box or a Motif
Label widget.
You write an alternative print handler routine in C or C++ and register its
name at the beginning of your stand-alone application.
The way you register a print handler depends on whether or not “the main
routine” (or first routine called) for your application is written in C or in M.
Note The print handlers and registration functions discussed in this section
are written for C applications. Although they will work in C++ applications,
we recommend that you use a C++ print handler and the C++ registration
routine mwSetPrintHandler() for C++ applications. See the MATLAB C++
Math Library User’s Guide for details about C++ print handlers.
5-44
Print Handlers
The first and last items in this list refer to print handlers.
5-45
5 Controlling Code Generation
• Take a single argument of type const char * that points to the text to be
displayed.
• Return void.
The print handler routine WinPrint in the example program illustrates one
possible approach to writing a print handler for a Windows program.
When the example WinMain routine prints the array returned by mlfMrank,
mlfPrintMatrix(R);
5-46
Print Handlers
• The print handler routine itself that deposits the text passed to it in an
output buffer
void WinPrint( char *text)
{
int cnt;
• The related function WinFlush that actually displays the text from the
output buffer in a Windows message box.
void WinFlush(void)
{
MessageBox(NULL, OutputBuffer, "MRANK", MB_OK);
mxFree(OutputBuffer);
}
For more details on mlfPrintMatrix, see the MATLAB C Math Library User’s
Guide.
5-47
5 Controlling Code Generation
Registering the print handler requires several steps, some performed in C and
some in M-code. To register a print handler from your main M-file, you call a
dummy print handler initialization function written in M-code. The MATLAB
Compiler translates that call into a call to the actual print handler
initialization function written in C or C++.
To set up for this translation, you must write two print handler initialization
functions:
You call the dummy print handler initialization function from your main
M-file. The MATLAB Compiler translates that call into a call to your print
handler initialization function written in C or C++.
Example Files
In this example, two M-files and one C file are built into a stand-alone
application. The main routine is mr.m.
function initprnt
%#external
5-48
Print Handlers
• myph.c contains the print handler and the print handler initialization
routine, in that order. In the example, this C file is written by the user.
#include "matlab.h"
#include “mr_external.h”
static void myPrintHandler(const char *s)
{
printf("%s\n",s);
}
void Mmr_initprnt(void)
{
mlfSetPrintHandler(myPrintHandler);
}
5-49
5 Controlling Code Generation
Naming the Print Handler Initialization Routine in C. When you write the print handler
initialization routine in C, you must follow the naming convention used by the
MATLAB C Math Library. This name will appear in a header file that is
generated by the MATLAB Compiler when it compiles the stub M-function,
initprnt in this example. See the earlier section, “Interfacing M-Code to C/
C++ Code,” for more information.
You should include this Compiler-generated header file when you define the C
function. For example, the print handler initialization routine developed here
is called MInitprnt and is found in mr_external.h.
Naming the Dummy Print Handler Initialization Routine in M-Code. When you name the
dummy print handler initialization routine in M-code, you must name it after
the base part of the actual print handler initialization routine (the one written
in C or C++).
For example, the dummy print handler initialization routine shown here is
called initprnt.
Writing the Initialization Routine in C. First, write the print handler initialization
routine in C. All print handler initialization functions register the name of the
print handler function by calling mlfSetPrintHandler, passing a pointer to the
print handler (the function name) as an argument.
Your initialization function must take no arguments and return void. For
example,
void Mmr_initprnt(void)
{
mlfSetPrintHandler(myPrintHandler);
}
Writing a Dummy Initialization Function in M-Code. Next, write the dummy print
handler initialization routine in M-code. The body of this function is empty, but
without the function declaration, the MATLAB Compiler can’t successfully
translate the call to initprnt in M-code into a call to MInitprnt() in C.
The function can be placed in the same M-file that defines the main mr.m in this
example. It is declared as function initprnt and contains the %#external
pragma.
5-50
Print Handlers
Initializing the Print Handler in Your Main M-File. Call the dummy print handler
initialization routine in the first executable line of your main M-file. For
example, in mr.m the call to initprnt immediately follows the function
declaration.
function mr(m)
initprnt; % Call print handler initialization routine
m=str2num(m);
r=mrank(m)
function initprnt
%#external
5-51
5 Controlling Code Generation
5-52
6
Optimizing Performance
Optimization Bundles . . . . . . . . . . . . . . . . 6-3
The only times you would choose not to optimize are if you are debugging your
code or you want to maintain the readability of your code.
6-2
Optimization Bundles
Optimization Bundles
All optimizations are controlled separately, and you can enable or disable any
of the optimizations. To simplify the process, you can use the provided bundles
of Compiler settings that allow you to select the most common optimization
options. For more information on bundles, see “-B <filename> (Bundle of
Compiler Settings)” on page 7-43.
• fold_scalar_mxarrays
• fold_non_scalar_mxarrays
• array_indexing
• optimize_integer_for_loops
• optimize_conditionals
6-3
6 Optimizing Performance
6-4
Optimizing Arrays
Optimizing Arrays
Scalar Arrays
(fold_scalar_mxarrays) When this optimization is enabled, all constant,
scalar-valued array operations are folded at compile time and are stored in a
constant pool that is created once at program initialization time. Folding
reduces the number of computations that are performed at runtime, thus
improving runtime performance.
Scalar folding can dramatically improve the performance of code that is
manipulating scalar arrays, but it makes the code less readable. For example,
function y = foo(x)
y = 2*pi*x;
Nonscalar Arrays
(fold_non_scalar_mxarrays) This optimization is very similar to
fold_scalar_mxarrays. It folds nonscalar mxArray values into compile-time
arrays that are initialized at program start-up. This can have a large
performance impact if you are constructing arrays that use [] or {} within a
loop. This optimization makes the code less readable. For example,
function y = test
y = [ 1 0; 0 1] * [ pi pi/2; -pi -pi/2 ];
6-5
6 Optimizing Performance
6-6
Optimizing Loops
Optimizing Loops
Simple Indexing
(array_indexing) This optimization improves the performance of simple one-
and two-dimensional array index expressions. Without this optimization, all
array indexing uses the fully general array indexing function, which is not
optimized for one- and two-dimensional indexing. With this optimization
enabled, indexing uses faster routines that are optimized for simple indexing.
For example,
function y = test(x,i1,i2);
y = x(i1,i2);
Loop Simplification
(optimize_integer_for_loops) This optimization detects when a loop starts
and increments with integers and replaces the loop with a much simpler loop
that uses C integer variables instead of array valued variables. The
performance improvements with this optimization can be dramatic.
6-7
6 Optimizing Performance
For example,
function test(x)
for i = 1:length(x)-1
x(i) = x(i) + x(i+1)
end
6-8
Optimizing Loops
...
for (; ; ) {
...
if (v_ == e_) {
break;
}
++v_;
}
mlfAssign(&i, mlfScalar(v_));
}
...
6-9
6 Optimizing Performance
Optimizing Conditionals
(optimize_conditionals) This optimization reduces the MATLAB conditional
operators to scalar C conditional operators when both operands are known to
be integer scalars. The Compiler “knows” that nargin, nargout, and for loop
control variables (when using the above optimization) are integer scalars. For
example,
function test(a,b,c,d)
if (nargin < 4)
d = 0.0;
end
6-10
7
Reference
Pragmas . . . . . . . . . . . . . . . . . . . . . . 7-4
%#external . . . . . . . . . . . . . . . . . . . . . 7-5
%#function . . . . . . . . . . . . . . . . . . . . . 7-6
%#mex . . . . . . . . . . . . . . . . . . . . . . . 7-7
Functions . . . . . . . . . . . . . . . . . . . . . 7-8
mbchar . . . . . . . . . . . . . . . . . . . . . . . 7-9
mbcharscalar . . . . . . . . . . . . . . . . . . . . 7-10
mbcharvector . . . . . . . . . . . . . . . . . . . . 7-11
mbint . . . . . . . . . . . . . . . . . . . . . . . 7-12
mbintscalar . . . . . . . . . . . . . . . . . . . . . 7-14
mbintvector . . . . . . . . . . . . . . . . . . . . . 7-15
mbreal . . . . . . . . . . . . . . . . . . . . . . . 7-16
mbrealscalar . . . . . . . . . . . . . . . . . . . . 7-17
mbrealvector . . . . . . . . . . . . . . . . . . . . 7-18
mbscalar . . . . . . . . . . . . . . . . . . . . . . 7-19
mbvector . . . . . . . . . . . . . . . . . . . . . . 7-20
reallog . . . . . . . . . . . . . . . . . . . . . . . 7-21
realpow . . . . . . . . . . . . . . . . . . . . . . 7-22
realsqrt . . . . . . . . . . . . . . . . . . . . . . 7-23
Pragmas
Functions
7-2
Command Line Tools
7-3
Pragmas
Pragmas
Pragmas are compiler-specific commands that provide special information to
the Compiler. This section contains the reference pages for the MATLAB
Compiler pragmas, %#external, %#function, and %#mex.
7-4
%#external
Purpose 7%#external
Pragma to call arbitrary C/C++ functions from your M-code.
Syntax %#external
Description The %#external pragma informs the Compiler that the implementation
version of the function (Mf) will be hand written and will not be generated from
the M-code. This pragma affects only the single function in which it appears,
and any M-function may contain this pragma (local, global, private, or method).
When using this pragma, the Compiler will generate an additional header file
called file_external.h or file_external.hpp, where file is the name of the
initial M-file containing the %#external pragma. This header file will contain
the extern declaration of the function that the user must provide. This function
must conform to the same interface as the Compiler-generated code. For more
information on the %#external pragma, see “Interfacing M-Code to C/C++
Code” in Chapter 5.
7-5
%#function
Purpose 7%#function
feval pragma.
Description This pragma informs the MATLAB Compiler that the specified function(s) will
be called through an feval, eval, or handle graphics callback. You need to
specify this pragma only to assist the Compiler in locating and automatically
compiling the set of functions when using the -h option.
If you are using the %#function pragma to define functions that are not
available in M-code, you should use the %#external pragma to define the
function. For example,
%#function myfunctionwritteninc
The function statement indicates that the function takes three inputs (a, b, c)
and returns a single output variable (y). No additional lines need to be present
in the M-file.
7-6
%#mex
Purpose 7%#mex
mex pragma.
Syntax %#mex
Description This pragma informs the MATLAB Compiler to select the MEX-file over an
existing M-file.
If you are using the %#function pragma to define functions that are not
available in M-code, you should use the %#external pragma to define the
function. For example,
function y = gamma(x)
%#mex
error('gamma MEX-file is missing');
7-7
Functions
Functions
This section contains the reference pages for the Compiler functions. Many of
these functions are included to maintain backward compatibility with previous
versions of the Compiler.
7-8
mbchar
Purpose 7mbchar
Assert variable is a MATLAB character string.
Syntax mbchar(x)
A char matrix is any scalar, vector, or matrix that contains only the char data
type.
Example This code in MATLAB causes mbchar to generate an error message because n
does not contain a char matrix.
n = 17;
mbchar(n);
??? Error using ==> mbchar
Argument to mbchar must be of class 'char'.
7-9
mbcharscalar
Purpose 7mbcharscalar
Assert variable is a character scalar.
Syntax mbcharscalar(x)
Note that mbcharscalar only tests x at the point in an M-file or MEX-file where
an mbcharscalar call appears. In other words, an mbcharscalar call tests the
value of x only once. If x becomes a vector after the mbcharscalar test,
mbcharscalar cannot issue an error message.
mbcharscalar defines a character scalar as any value that meets the criteria of
both mbchar and mbscalar.
7-10
mbcharvector
Purpose 7mbcharvector
Assert variable is a character vector, i.e., a MATLAB string.
Syntax mbcharvector(x)
mbcharvector defines a char vector as any value that meets the criteria of both
mbchar and mbvector. Note that mbcharvector considers char scalars as char
vectors as well.
7-11
mbint
Purpose 7mbint
Assert variable is integer.
Syntax mbint(n)
7-12
mbint
mbint does not consider the value of x an integer because one of the parts (the
imaginary) has a fractional component.
x = 4 + 7.5i;
Example This code in MATLAB causes mbint to generate an error message because n
does not hold an integer value.
n = 17.4;
mbint(n);
??? Error using ==> mbint
Argument to mbint must be integer.
7-13
mbintscalar
Purpose 7mbintscalar
Assert variable is integer scalar.
Syntax mbintscalar(n)
Note that mbintscalar only tests x at the point in an M-file or MEX-file where
an mbintscalar call appears. In other words, an mbintscalar call tests the
value of x only once. If x becomes a vector after the mbintscalar test,
mbintscalar cannot issue an error message.
mbintscalar defines an integer scalar as any value that meets the criteria of
both mbint and mbscalar.
7-14
mbintvector
Purpose 7mbintvector
Assert variable is integer vector.
Syntax mbintvector(n)
Note that mbintvector only tests x at the point in an M-file or MEX-file where
an mbintvector call appears. In other words, an mbintvector call tests the
value of x only once. If x becomes a two-dimensional matrix after the
mbintvector test, mbintvector cannot issue an error message.
mbintvector defines an integer vector as any value that meets the criteria of
both mbint and mbvector. Note that mbintvector considers integer scalars to
be integer vectors as well.
7-15
mbreal
Purpose 7mbreal
Assert variable is real.
Syntax mbreal(n)
Example This code in MATLAB causes mbreal to generate an error message because n
contains an imaginary component.
n = 17 + 5i;
mbreal(n);
??? Error using ==> mbreal
Argument to mbreal must be real.
7-16
mbrealscalar
Purpose 7mbrealscalar
Assert variable is real scalar.
Syntax mbrealscalar(n)
mbrealscalar defines a real scalar as any value that meets the criteria of both
mbreal and mbscalar.
7-17
mbrealvector
Purpose 7mbrealvector
Assert variable is a real vector.
Syntax mbrealvector(n)
mbrealvector defines a real vector as any value that meets the criteria of both
mbreal and mbvector. Note that mbrealvector considers real scalars to be real
vectors as well.
7-18
mbscalar
Purpose 7mbscalar
Assert variable is scalar.
Syntax mbscalar(n)
Example This code in MATLAB causes mbscalar to generate an error message because
n does not hold a scalar.
n = [1 2 3];
mbscalar(n);
??? Error using ==> mbscalar
Argument of mbscalar must be scalar.
7-19
mbvector
Purpose 7mbvector
Assert variable is vector.
Syntax mbvector(n)
Example This code in MATLAB causes mbvector to generate an error message because
the dimensions of n are 2-by-2.
n = magic(2)
n =
1 3
4 2
mbvector(n)
??? Error using ==> mbvector
Argument to mbvector must be a vector.
7-20
reallog
Purpose 7reallog
Natural logarithm for nonnegative real inputs.
Syntax Y = reallog(X)
7-21
realpow
Purpose 7realpow
Array power function for real-only output.
Syntax Z = realpow(X,Y)
realpow is similar to the array power operator (.^) of MATLAB. However, the
range of .^ is much broader than the range of realpow. (The range of .^
includes all real and all imaginary numbers.) If X raised to the Y power yields
a complex answer, then you must use .^ instead of realpow. However, if X
raised to the Y power yields a real answer, then you should use realpow for two
reasons.
First, subsequent access of Z may execute more efficiently if Z is calculated with
realpow rather than .^. Using realpow forces the MATLAB Compiler to
impute that Z, X, and Y are real. Using .^ typically forces the MATLAB
Compiler to impute the complex type to Z.
Second, the compiled version of realpow may run somewhat faster than the
compiled version of .^. (However, the interpreted version of realpow may run
somewhat slower than the interpreted version of .^.)
7-22
realsqrt
Purpose 7realsqrt
Square root for nonnegative real inputs.
Syntax Y = realsqrt(X)
Description realsqrt(X) returns the square root of the elements of X. The domain of
realsqrt is the set of all nonnegative real numbers. If X is negative or complex,
realsqrt issues an error message.
7-23
Command Line Tools
7-24
mbuild
Purpose 7mbuild
Compile and link source files that call functions in the MATLAB C/C++ Math
Library or MATLAB C/C++ Graphics Library into a stand-alone executable or
shared library.
Description mbuild is a script that supports various options that allow you to customize the
building and linking of your code. This table lists the mbuild options. If no
platform is listed, the option is available on both UNIX and Microsoft Windows.
Option Description
7-25
mbuild
Option Description
7-26
mbuild
Option Description
7-27
mbuild
Option Description
7-28
mbuild
Option Description
Note Some of these options (-f, -g, and -v) are available on the mcc
command line and are passed along to mbuild. Others can be passed along
using the -M option to mcc. For details on the -M option, see the mcc reference
page.
7-29
mcc
Purpose 7mcc
Invoke MATLAB Compiler.
Description mcc is the MATLAB command that invokes the MATLAB Compiler. You can
issue the mcc command either from the MATLAB command prompt (MATLAB
mode) or the DOS or UNIX command line (stand-alone mode).
You can group options that do not take arguments by preceding the list of
option flags with a single dash (-), for example,
mcc -mg myfun
Options that take arguments cannot be combined unless you place the option
with its arguments last in the list. For example, these formats are valid.
mcc -m -A full myfun % Options listed separately
mcc -mA full myfun % Options combined, A option last
In cases where you have more than one option that takes arguments, you can
only include one of those options in a combined list and that option must be
last. You can place multiple combined lists on the mcc command line.
If you include any C or C++ filenames on the mcc command line, the files are
passed directly to mex or mbuild, along with any Compiler-generated C or C++
files.
7-30
mcc
compilation, you can use one simple option, i.e., macro, that allows you to
quickly accomplish basic compilation tasks. If you want to take advantage of
the power of the Compiler, you can do whatever you desire to do by choosing
various Compiler options.
This table shows the relationship between the macro approach to accomplish a
standard compilation and the multioption alternative.
7-31
mcc
This table shows the five options that compose the -m macro and the
information that they provide to the Compiler.
Option Function
Changing Macro Options. You can change the meaning of a macro option by
editing the corresponding macro_option file bundle file in <matlab>/toolbox/
compiler/bundles. For example, to change the -x macro, edit the file
macro_option_x in the bundles directory.
7-32
mcc
mcc searches for the mccstartup file in these two directories in the order shown
above. If it finds an mccstartup file, it reads it and processes the options within
the file as if they had appeared on the mcc command line before any actual
command line options. Both the mccstartup file and the -B option are
processed the same way.
Note If you need to change the meaning of a macro to satisfy your individual
requirements, you should create or modify your mccstartup file in the
preferences directory. Changing the file macro_option_x in the bundles
directory changes the option for all Compiler users. To see the name of your
preferences directory, type prefdir at the command prompt.
2 Place this file in your preferences directory. To do so, run the following
commands at the MATLAB prompt.
cd(prefdir); mccsavepath;
These commands save your current MATLAB path to a file named mccpath
in your user preferences directory. (Type prefdir to see the name of your
preferences directory.)
The stand-alone version of the MATLAB Compiler searches for the mccpath file
in your current directory and then your preferences directory. If it finds an
mccpath file, it processes the directories specified within the file and uses them
to initialize its search path. Note that you may still use the -I option on the
command line or in mccstartup files to add other directories to the search path.
Directories specified this way are searched after those directories specified in
the mccpath file.
7-33
mcc
is equivalent to
mcc -t -W main -L C -T link:exe -h -W none test.m
In this example, there are two conflicting -W options. After working from left to
right, the Compiler determines that the rightmost option takes precedence,
namely, -W none, and the Compiler does not generate a wrapper.
Note Macros and regular options may both affect the same settings and may
therefore override each other depending on their order in the command line.
1 Breaks the full name into the corresponding path- and filenames (<path>
and <file>).
2 Replaces the full pathname in the argument list with “-I <path> <file>”.
For example,
mcc -m /home/user/myfile.m
would be treated as
mcc -m -I /home/user myfile.m
In rare situations, this behavior can lead to a potential source of confusion. For
example, suppose you have two different M-files that are both named myfile.m
and they reside in /home/user/dir1 and /home/user/dir2. The command
mcc -m -I /home/user/dir1 /home/user/dir2/myfile.m
7-34
mcc
would be equivalent to
mcc -m -I /home/user/dir1 -I /home/user/dir2 myfile.m
The Compiler finds the myfile.m in dir1 and compiles it instead of the one in
dir2 because of the behavior of the -I option. If you are concerned that this
might be happening, you can specify the -v option and then see which M-file
the Compiler parses. The -v option prints the full pathname to the M-file.
creates bell.mex. The entry point of bell.mex is the compiled code from
bell.m. The compiled version of bell.m can call the compiled version of
watson.m. However, compiling as
creates watson.mex. The entry point of watson.mex is the compiled code from
watson.m. The code from bell.m never gets executed.
As another example, suppose that x.m calls y.m and that y.m calls z.m. In this
case, make sure that x.m is the first M-file on the command line. After x.m, it
does not matter which order you specify y.m and z.m.
7-35
mcc
Category Purpose
Macro Options
The macro options provide a simplified way to accomplish basic compilation
tasks.
7-36
mcc
7-37
mcc
-A (Annotation Control for Output Source). Control the type of annotation in the
resulting C/C++ source file. The types of annotation you can control are:
To control the M-file code that is included in the generated C/C++ source, use
mcc -A annotation:type …
This table shows the available types of code and comment annotation options.
type Description
7-38
mcc
To control the #line preprocessor directives that are included in the generated
C/C++ source, use
mcc -A line:setting …
Setting Description
To control if run-time error messages report the source file and line number,
use
mcc -A debugline:on …
Setting Description
For example:
To include all of your M-code, including comments, in the generated file and the
standard #line preprocessor directives, use
mcc -A annotation:all -A line:on …
or
mcc -A line:on … (The default is all for code/comment inclusion.)
7-39
mcc
-F <option> (Formatting). Control the formatting of the generated code. This table
shows the available options.
<Option> Description
-G -A debugline:on -O none
7-40
mcc
-l (Line Numbers) . Generate C/C++ code that prints filename and line numbers
on run-time errors. This option flag is useful for debugging, but causes the
executable to run slightly slower. This option is equivalent to
mcc -A debugline:on …
-O <option> (Optimization Options). Optimizes your M-file source code so that the
performance of the generated C/C++ code may be faster than the performance
of the M-code in the MATLAB interpreter. This table shows the available
options.
<Option> Description
• fold_scalar_mxarrays
• fold_non_scalar_mxarrays
• array_indexing
• optimize_integer_for_loops
• optimize_conditionals
-u (Number of Inputs). Provide more control over the number of valid inputs for
your Simulink S-function. This option specifically sets the number of inputs (u)
for your function. If -u is omitted, the input will be dynamically sized. (Used
with -S option.)
7-41
mcc
<Type> Description
Caution When generating function wrappers, you must specify all M-files
that are being linked together on the command line. These files are used to
produce the initialization and termination functions as well as global variable
definitions. If the functions are not specified in this manner, undefined
symbols will be produced at link time or run-time crashes may occur.
-y (Number of Outputs). Provides more control over the number of valid outputs
for your Simulink S-function. This option specifically sets the number of
outputs (y) for your function. If -y is omitted, the output will be dynamically
sized. (Used with -S option.)
7-42
mcc
-c (C Code Only). Generate C code but do not invoke mex or mbuild, i.e., do not
produce a MEX-file or stand-alone application. This is equivalent to -T
codegen placed at the end of the mcc command line.
-d <directory> (Output Directory). Place the output files from the compilation in the
directory specified by the -d option.
-h (Helper Functions). Compile helper functions. Any helper functions that are
called will be compiled into the resulting MEX or stand-alone application. The
-m option automatically compiles all helper functions, so -m effectively calls -h.
Using the -h option is equivalent to listing the M-files explicitly on the mcc
command line.
The -h option purposely does not include built-in functions or functions that
appear in the MATLAB M-File Math Library portion of the C/C++ Math
Libraries. This prevents compiling functions that are already part of the C/C++
Math Libraries. If you want to compile these functions as helper functions, you
should specify them explicitly on the command line. For example, use
mcc -m minimize_it fminsearch
instead of
mcc -m -h minimize_it
-I <directory> (Directory Path). Add a new directory path to the list of included
directories. Each -I option adds a directory to the end of the current search
path. For example,
-I <directory1> -I <directory2>
7-43
mcc
would set up the search path so that directory1 is searched first for M-files,
followed by directory2. This option is important for stand-alone compilation
where the MATLAB path is not available.
-T <target> (Output Stage). Specify the desired output stage. This table gives the
possible values of target.
<Target> Description
where <bin> can be mexlibrary, mex, exe, or lib. mex and mexlibrary
use the mex script to build a MEX-file; exe uses the mbuild script to
build an executable; lib uses mbuild to build a shared library.
7-44
mcc
The -v option passes the -v option to mex or mbuild and displays information
about mex or mbuild.
-w (Warning). Display warning messages. This table shows the various ways you
can use the -w option.
Syntax Description
7-45
mcc
mbuild/mex Options
-f <filename> (Specifying Options File). Use the specified options file when calling
mex or mbuild. This option allows you to use different compilers for different
invocations of the MATLAB Compiler. This option is a direct pass-through to
the mex or mbuild script. See “External Interfaces/API” for more information
about using this option with the mex script.
Note Although this option works as documented, it is suggested that you use
mex -setup or mbuild -setup to switch compilers.
-g (Debug Only). Cause mex or mbuild to invoke the C/C++ compiler with the
appropriate C/C++ compiler options for debugging. You should specify -g if you
want to debug the MEX-file or stand-alone application with a debugger.
-M "string" (Direct Pass Through). Pass string directly to the mex or mbuild script.
This provides a useful mechanism for defining compile-time options, e.g., -M
"-Dmacro=value".
Note Multiple -M options do not accumulate; only the last -M option is used.
-z <path> (Specifying Library Paths). Specify the path to use for library and include
files. This option uses the specified path for compiler libraries instead of the
path returned by matlabroot.
7-46
mcc
Make a C translation and a MEX-file for myfun.m. Also translate and include
all M-functions called directly or indirectly by myfun.m. Incorporate the full
text of the original M-files into their corresponding C files as C comments.
mcc -x -h -A annotation:all myfun
7-47
mcc
Note On PCs, filenames ending with .o above would actually end with .obj.
7-48
A
MATLAB Compiler
Quick Reference
Common Uses of the Compiler . . . . . . . . . . . . A-2
mcc . . . . . . . . . . . . . . . . . . . . . . . . A-4
A MATLAB Compiler Quick Reference
A-2
Create a C++ Library. To create a C++ library, use
mcc -p -W lib:libfoo -T compile:lib foo.m
Note You can add the -g option to any of these for debugging purposes.
A-3
A MATLAB Compiler Quick Reference
mcc
Bold entries in the Comment/Options column indicate default values.
f filename Uses the specified options mex -setup and mbuild -setup are
file, filename recommended.
F option Specifies format parameters option = list
expression-indent:n
page-width:n
statement-indent:n
g Generates debugging
information
A-4
mcc
A-5
A MATLAB Compiler Quick Reference
A-6
mcc
A-7
A MATLAB Compiler Quick Reference
A-8
B
Error and Warning
Messages
Compile-Time Errors . . . . . . . . . . . . . . . . B-3
This appendix lists and describes error messages and warnings generated by
the MATLAB Compiler. Compile-time messages are generated during the
compile or link phase. It is useful to note that most of these compile-time error
messages should not occur if MATLAB can successfully execute the
corresponding M-file. Run-time messages are generated when the executable
program runs.
The sections in this appendix are:
• “Compile-Time Errors”
• “Warning Messages”
• “Run-Time Errors”
Note When using the MATLAB Compiler, if you receive an Internal Error
message, record the specific message and report it to Technical Support at The
MathWorks at [email protected].
B-2
Compile-Time Errors
Compile-Time Errors
Error: An error occurred while shelling out to mex/mbuild (error code = errorno). Unable to
build executable (specify the -v option for more information). The Compiler reports this
error if mbuild or mex generates an error.
Error: An error occurred writing to file "filename": reason. The file could not be
written. The reason is provided by the operating system. For example, you may
not have sufficient disk space available to write the file.
Error: Cannot write file "filename" because MCC has already created a file with that name, or
a file with that name was specified as a command line argument. The Compiler has
been instructed to generate two files with the same name. For example,
mcc -W lib:liba liba -t % Incorrect
Error: Could not check out a Compiler license. No additional Compiler licenses are
available for your workgroup.
Error: Could not find license file "filename". (Windows only) The license.dat file
could not be found in <MATLAB>\bin.
Error: Could not run mbuild. The MATLAB C/C++ Math Library must be installed in order to
build stand-alone applications. Install the MATLAB C/C++ Math Library.
Error: File: "filename" not found. A specified file could not be found on the path.
Verify that the file exists and that the path includes the file’s location. You can
use the -I option to add a directory to the search path
Error: File: "filename" is a script M-file which cannot be compiled with the current Compiler.
The MATLAB Compiler cannot compile script M-files. To learn how to convert
script M-files to function M-files, see “Converting Script M-Files to Function
M-Files” in Chapter 3.
Error: File: filename Line: # Column: # != is not a MATLAB operator. Use ~= instead. Use
the MATLAB relational operator ~= (not equal).
B-3
B Error and Warning Messages
Error: File: filename Line: # Column: # () indexing must appear last in an index expression.
If you use ordinary array indexing () to index into an expression, it must be
last in the index expression. For example, you can use X(1).value and
X{2}(1), but you cannot use X.value(1) or X(1){2}.
Error: File: filename Line: # Column: # A CONTINUE may only be used within a FOR or WHILE
loop. Use CONTINUE to pass control to the next iteration of a FOR or WHILE loop.
Error: File: filename Line: # Column: # A function declaration cannot appear within a script
M-file. There is a function declaration in the file to be compiled, but it is not at
the beginning of the file. Scripts cannot have any function declarations;
function M-files must start with a function.
Error: File: filename Line: # Column: # Assignment statements cannot produce a result. An
assignment statement cannot be used in a place where an expression, but not
a statement, is expected. In particular, this message often identifies errors
where an assignment was used, but an equality test was intended. For
example,
if x == y, z = w; end % Correct
if x = y, z = w; end % Incorrect
Error: File: filename Line: # Column: # A variable cannot be made storageclass1 after being
used as a storageclass2. You cannot change a variable’s storage class (global/
local/persistent). Even though MATLAB allows this type of change in scope, the
Compiler does not.
Error: File: filename Line: # Column: # An array for multiple LHS assignment must be a vector.
If the left-hand side of a statement is a multiple assignment, the list of
left-hand side variables must be a vector. For example,
[p1, p2, p3] = myfunc(a) % Correct
[p1; p2; p3] = myfunc(a) % Incorrect
Error: File: filename Line: # Column: # An array for multiple LHS assignment cannot be
empty. If the left-hand side of a statement is a multiple assignment, the list of
left-hand side variables cannot be empty. For example,
[p1, p2, p3] = myfunc(a) % Correct
[ ] = myfunc(a) % Incorrect
B-4
Compile-Time Errors
Error: File: filename Line: # Column: # An array for multiple LHS assignment cannot contain
token. If the left-hand side of a statement is a multiple assignment, the vector
cannot contain this token. For example, you cannot assign to constants.
[p1] = myfunc(a) % Correct
[3] = myfunc(a) % Incorrect
Error: File: filename Line: # Column: # Expected a variable, function, or constant, found
"string". There is a syntax error in the specified line. See the online MATLAB
Function Reference pages accessible from the Help browser.
Error: File: filename Line: # Column: # Expected one of , ; % or EOL, got "string". There is
a syntax error in the specified line. See the online MATLAB Function
Reference pages accessible from Help.
Error: File: filename Line: # Column: # Functions cannot be indexed using {} or . indexing.
You cannot use the cell array constructor, {}, or the structure field access
operator, ., to index into a function.
Error: File: filename Line: # Column: # Indexing expressions cannot return multiple results.
There is an assignment in which the left-hand side takes multiple values, but
the right-hand side is not a function call but rather a structure access. For
example,
[x, y] = f(z) % Correct
[x, y] = f.z % Incorrect
Error: File: filename Line: # Column: # Invalid multiple left-hand-side assignment. For
example, you try to assign to constants
[] = sin(1); % Incorrect
Error: File: filename Line: # Column: # MATLAB assignment cannot be nested. You cannot
use a syntax such as x = y = 2. Use y = 2, x = y instead.
Error: File: filename Line: # Column: # Missing operator, comma, or semicolon. There is a
syntax error in the file. Syntactically, an operator, a comma, or a semicolon is
expected, but is missing. For example,
if x == y, z = w; end % Correct
if x == y, z = w end % Incorrect
B-5
B Error and Warning Messages
Error: File: filename Line: # Column: # Missing variable or function. An illegal name was
used for a variable or function. For example,
x % Correct
_x % Incorrect
Error: File: filename Line: # Column: # Only functions can return multiple values. In this
example, foo must be a function, it cannot be a variable.
[a, b] = foo;
Error: File: filename Line: # Column: # "string1" expected, "string2" found. There is a
syntax error in the specified line. See the online MATLAB Function Reference
pages accessible from the online Help.
Error: File: filename Line: # Column: # The end operator can only be used within an array
index expression. You can use the end operator in an array index expression such
as sum(A(:, end)). You cannot use the end operator outside of such an
expression, for example, y = 1 + end.
Error: File: filename Line: # Column: # The name "parametername" occurs twice as an input
parameter. The variable names specified on the function declaration line must
be unique. For example,
function foo(bar1, bar2) % Correct
function foo(bar, bar) % Incorrect
Error: File: filename Line: # Column: # The name "parametername" occurs twice as an output
parameter. The variable names specified on the function declaration line must
be unique. For example,
function [bar1, bar2] = foo % Correct
function [bar, bar] = foo % Incorrect
Error: File: filename Line: # Column: # The 'operatorname' operator may only produce a single
output. The primitive operator produces only a single output. For example,
x = 1:10; % is correct
[x, y] = 1:10; % is incorrect
Error: File: filename Line: # Column: # The PERSISTENT declaration must precede any use of
the variable variablename. In the text of the function, there is a reference to the
variable before the persistent declaration.
B-6
Compile-Time Errors
Error: File: filename Line: # Column: # The single colon operator (:) can only be used within an
array index expression. You can only use the : operator by itself as an array
index. For example, A(:) = 5; is okay, but y = :; is not.
Error: File: filename Line: # Column: # The variable variablename was mentioned more than
once as an input. The argument list has a repeated variable. For example,
function y = myfun(x, x) % Incorrect
Error: File: filename Line: # Column: # The variable variablename was mentioned more than
once as an output. The return value vector has a repeated variable. For example,
function [x, x] = myfun(y) % Incorrect
Error: File: filename Line: # Column: # This statement is incomplete. Variable arguments cannot
be made global or persistent. The variables varargin and varargout are not like
other variables. They cannot be declared either global or persistent. For
example,
global varargin % Incorrect
Error: File: filename Line: # Column: # Variable argument (varargin) must be last in input
argument list. The function call must specify the required arguments first
followed by varargin. For example,
function [out1, out2] = example1(a, b, varargin) % Correct
function [out1, out2] = example1(a, varargin, b) % Incorrect
Error: File: filename Line: # Column: # Variable argument (varargout) must be last in output
argument list. The function call must specify the required arguments first
followed by varargout. For example,
function [i, j, varargout]= ex2(x1, y1, x2, y2, val) % Correct
function [i, varargout, j]= ex2(x1, y1, x2, y2, val) % Incorrect
Error: File: filename Line: # Column: # variablename has been declared both as GLOBAL and
PERSISTENT. Declare variables as either GLOBAL or PERSISTENT.
Error: Found illegal whitespace character in command line option: "string". The strings on the
left and right side of the space should be separate arguments to MCC. For example,
mcc('-A', 'none') % Correct
mcc('-A none') % Incorrect
B-7
B Error and Warning Messages
Error: Improper usage of option -optionname. Type "mcc -?" for usage information. You
have incorrectly used a Compiler option. For more information about Compiler
options, see the section, “MATLAB Compiler Option Flags,” in Chapter 7 or
type mcc -? at the command prompt.
Error: "languagename" is not a known language. The dialect option was given a
language argument for which there is no support yet. For example,
mcc -m -D japanese sample.m % Correct
mcc -m -D german sample.m % Incorrect
Error: libraryname library not found. MATLAB has been installed incorrectly.
Error: MEX-File "mexfilename" cannot be compiled into P-Code. Only M-files can be
compiled into P-code; MEX-files cannot be compiled into P-code.
Error: No source files were specified (-? for help). You must provide the Compiler
with the name of the source file(s) to compile.
Error: On UNIX, the name of an MLIB-file must begin with the letters "lib". 'filename' does not
adhere to this rule. The mlib file specified on the command line does not start
with the letters “lib” and the file being compiled uses procedures in that library.
Error: "optionname" is not a valid -option option argument. You must use an
argument that corresponds to the option. For example,
mcc -L Cpp … % Correct
mcc -L COBOL … % Incorrect
Error: Out of memory. Typically, this message occurs because the Compiler
requests a larger segment of memory from the operating system than is
currently available. Adding additional memory to your system could alleviate
this problem.
Error: Previous warning treated as error. When you use the -w error option, this
error displays immediately after a warning message.
Error: The argument after the -option option must contain a colon. The format for this
argument requires a colon. For more information, see “MATLAB Compiler
Option Flags,” in Chapter 7 or type mcc -? at the command prompt.
B-8
Compile-Time Errors
Error: The environment variable MATLAB must be set to the MATLAB root directory. On
UNIX, the MATLAB and LM_LICENSE_FILE variables must be set. The mcc shell
script does this automatically when it is called the first time.
Error: The file filename cannot be written. When generating an mlib file, the
Compiler cannot write out the mlib file.
Error: The license manager failed to initialize (error code is errornumber). You do not
have a valid Compiler license or no additional Compiler licenses are available.
Error: The option -option is invalid in modename mode (specify -? for help). The specified
option is not available.
For example, you can use mcc -vc, but you cannot use
mcc -Ac annotation:all.
Error: The options specified will not generate any output files.
Please use one of the following options to generate an executable output file:
-x (generates a MEX-file executable using C)
-m (generates a stand-alone executable using C)
-p (generates a stand-alone executable using C++)
-S (generates a Simulink MEX S-function using C)
-B sgl (generates a stand-alone graphics library executable using C (requires the SGL))
-B sglcpp (generates a stand-alone graphics library executable using C++ (requires the SGL))
-B pcode (generates a MATLAB P-code file)
Or type mcc -? for more usage information. Use one of these options or another
option that generates output file(s). See the section, “MATLAB Compiler
Option Flags,” in Chapter 7 or type mcc -? at the command prompt for more
information.
Error: The specified file "filename" cannot be read. There is a problem with your
specified file. For example, the file is not readable because there is no read
permission.
B-9
B Error and Warning Messages
Error: The -option option cannot be combined with other options. The -V2.0 option
must appear separate from other options on the command line. For example,
mcc -V2.0 -L Cpp … % Correct
mcc -V2.0L Cpp … % Incorrect
Error: This version of MCC does not support the creation of C++ MEX code. You cannot
create C++ MEX functions with the current Compiler.
Error: Unable to open file "filename":<string>. There is a problem with your specified
file. For example, there is no write permission to the output directory, or the
disk is full.
Error: Unable to set license linger interval (error code is errornumber). A license
manager failure has occurred. Contact Technical Support at The MathWorks
with the full text of the error message.
Error: Uninterpretable width set on command line "commandline". The argument to the
page width option was not interpretable as a number.
Error: Unknown annotation option: optionname. An invalid string was specified after
the -A option. For a complete list of the valid annotation options, see “MATLAB
Compiler Option Flags,” in Chapter 7 or type mcc -? at the command prompt.
B-10
Compile-Time Errors
Error: Unrecognized option: -option. The option is not one of the valid options for
this version of the Compiler. See the section, “MATLAB Compiler Option
Flags,” in Chapter 7 for a complete list of valid options for Compiler 2.1 or type
mcc -? at the command prompt.
Error: Use "-V2.0" to specify desired version. You specified -V without a version
number. You must use -V2.0 if you specify a version number.
Error: versionnumber is not a valid version number. Use "-V2.0". If you specify a
Compiler version number, it must be -V2.0. The default is -V2.0.
B-11
B Error and Warning Messages
Warning Messages
This section lists the warning messages that the MATLAB Compiler 2.1 can
generate. Using the -w option for mcc, you can control which messages are
displayed. Each warning message contains a description and the warning
message identifier string (in parentheses) that you can enable or disable with
the -w option. For example, to enable the display of warnings related to
undefined variables, you can use
mcc -w enable:undefined_variable …
To enable all warnings except those generated by the save command, use
mcc -w enable -w disable:save_options …
For additional information about the -w option, see “MATLAB Compiler Option
Flags” in Chapter 7.
Warning: A line has number characters, violating the maximum page width width.
(max_page_width_violation) To increase the maximum page width, use the
-F page-width:n option and set n to a larger value.
Warning: File: filename Line: # Column: # A BREAK statement appeared outside of a loop. This
BREAK is interpreted as a RETURN. (break_without_loop) The break statement
should be used in conjunction with the for or while statements. When not used
in conjunction with these statements, the break statement acts as a return
from a function.
B-12
Warning Messages
Warning: File: filename Line: # Column: # The call to function "functionname" on this line could
not be bound to a function that is known at compile time. A run-time error will occur if this
code is executed. (no_matching_function) The called function was not found on
the search path.
Warning: File: filename Line: # Column: # Attempt to clear value when it has not been
previously defined. (clear_undefined_value) The variable was cleared with the
clear command prior to being defined.
Warning: File: filename Line: # Column: # Future versions of MATLAB will require that
whitespace, a comma, or a semicolon separate elements of a matrix. Please type "help
matrix_element_separators" at the MATLAB prompt for more information.
(separator_needed) It is still possible to leave out all separators when
constructing a matrix. For example, [5.5.5] has no separators. It is equivalent
to [5.5, 0.5].
Warning: File: filename Line: # Column: # References to "functionname" require the C/C++
Graphics Library when executing in stand-alone mode. You must specify -B sgl or -B sglcpp in
order to use the C/C++ Graphics Library. A run-time error will occur if the C/C++ Graphics
Library is not present. (using_graphics_function) This warning is produced when
a Graphics Library call is present in the code. It is only generated when
producing the main or library wrapper and not during normal compilation,
unless it is specifically enabled.
Warning: File: filename Line: # Column: # The #function pragma expects a list of function
names. (pragma_function_missing_names) This pragma informs the MATLAB
Compiler that the specified function(s) provided in the list of function names
will be called through an feval call. This is used so that the -h option will
automatically compile the selected functions.
B-13
B Error and Warning Messages
Warning: File: filename Line: # Column: # The call to function "functionname" on this line
passed quantity1 inputs and the function is declared with quantity2. A run-time error will occur
if this code is executed. (too_many_inputs) There is an inconsistency between the
number of formal and actual inputs to the function.
Warning: File: filename Line: # Column: # The call to function "functionname" on this line
requested quantity1 outputs and the function is declared with quantity2. A run-time error will
occur if this code is executed. (too_many_outputs) There is an inconsistency
between the number of formal and actual outputs for the function.
Warning: File: filename Line: # Column: # The clear function cannot process the "optionname"
argument in compiled code. (clear_cannot_handle_flag) You cannot use clear
variables, clear mex, clear functions, or clear all in compiled M-code.
Warning: File: filename Line: # Column: # The clear statement did not specifically list the names
of variables to be cleared as constant strings. A run-time error will be reported if this code is
executed. (clear_non_constant_strings) Use one of the forms of the clear
command that contains the names of the variables to be cleared. Use clear
name or clear('name'); do not use clear(name).
Warning: File: filename Line: # Column: # The Compiler does not support the optionname
option to save. This option is ignored. (save_option_ignored) You cannot use
-ascii, -double, or -tabs with the save command in compiled M-code.
Warning: File: filename Line: # Column: # The filename provided to load (save) was a cell array
or structure index that could possibly expand into a comma separated list. An error will occur
at run-time if a comma list is present for the filename. (load_save_filename) The
Compiler needs to know statically the number of variables that are involved in
a load or save. If a cell array is involved, the Compiler cannot make that
determination, and the generated code may behave differently from MATLAB.
Warning: File: filename Line: # Column: # The "functionname" function is only available in
MEX mode. A run-time error will occur if this code is executed in stand-alone mode.
(using_mex_only_function) This warning is produced if you call any built-in
function that is only available in mex mode. It is only generated when producing
the main or lib wrapper and not during normal compilation, unless specifically
enabled.
B-14
Warning Messages
Warning: File: filename Line: # Column: # The load statement cannot be translated unless it
specifically lists the names of variables to be loaded as constant strings.
(load_without_constant_strings) Use one of the forms of the load command
that contains the names of the variables to be loaded, for example,
load filename num or y = load('filename')
Warning: File: filename Line: # Column: # The logical expression(s) involving OR and AND
operators may have returned a different result in previous versions of MATLAB due to a change
in logical operator precedence. Use parentheses to make your code insensitive to this change.
Please type "help precedence" for more information. (and_or_precedence) Starting in
MATLAB 6.0, the precedence of the logical AND (&) and logical OR (|) operators now
obeys the standard relationship (AND being higher precedence than OR) and
the formal rules of boolean algebra as implemented in most other programming
languages, as well as Simulink and Stateflow.
Previously, MATLAB would incorrectly treat the expression
y = a&b | c&d
as
y = (((a&b) |c) &d);
The form, y = a&b | c&d, will not elicit the warning message from the
Compiler. We recommend that you use parentheses to get the same behavior
now and in the future.
Warning: File: filename Line: # Column: # The MATLAB Compiler does not currently support
MATLAB object-oriented programming. References to the method "methodname" will produce
a run-time error. (matlab_method_used) This warning occurs if the file being
compiled references a function that has only a method definition.
Warning: File: filename Line: # Column: # The save statement cannot be translated unless it
specifically lists the names of variables to be saved as constant strings.
(save_without_constant_strings) Use one of the forms of the save command
that contains the names of the variables to be saved, for example,
save filename num
B-15
B Error and Warning Messages
Warning: File: filename Line: # Column: # The second output argument from the
"functionname" function is only available in MEX mode. A run-time error will occur if this code
is executed in stand-alone mode. (unix_dos_second_argument) The DOS command
can be called with two output arguments. That form cannot be compiled in
stand-alone mode. This warning occurs if the DOS command was called with
two output arguments in a file that is being compiled in stand-alone mode. For
example,
[r, s] = dos('ls'); % causes a warning when compiling stand-alone
Warning: File: filename Line: # Column: # This load (save) statement referred to variable
"variablename" that was not referenced in the function. (load_save_unreferenced)
This warning occurs if a variable is loaded (saved) via a load (save) command,
but then does not occur elsewhere in scope.
Warning: File: filename Line: # Column: # name has been used as both a function and a
variable, the variable is ignored. (inconsistent_variable) When a name represents
both a function and a variable, it is used as the function only.
Warning: File: filename Line: # Column: # "variablename" has not been defined prior to use
on this line. (undefined_variable) Variables should be defined prior to use.
Warning: Line: # Column: # Function with duplicate name " functionname" cannot be called.
(duplicate_function_name) This warning occurs when an M-file contains more
than one function with the same name.
Warning: filename is a P-file being referenced from "filename". NOTE: A link error will be
produced if a call to this function is made from stand-alone mode. (mex_or_p_file) The
Compiler cannot generate a call to a function in a P-file for stand-alone code.
The warning occurs if a call to a function that is defined in a P-file is detected.
B-16
Warning Messages
Warning: M-file "filename" was specified on the command line with full path of "pathname",
but was found on the search path in directory "directoryname" first.
(specified_file_mismatch) The Compiler detected an inconsistency between the
location of the M-file as given on the command line and in the search path. The
Compiler uses the location in the search path. This warning occurs when you
specify a full pathname on the mcc command line and a file with the same base
name (filename) is found earlier on the search path. This warning is issued in
the following example if the file afile.m exists in both dir1 and dir2.
mcc -x -I /dir1 /dir2/afile.m
Warning: Overriding the -F page-width setting to width due to presence of -A line:on setting.
(page_width_override) The -A line:on setting overrides the page width. This
warning reminds you that the -F setting, although present, has no effect.
Warning: The function "functionname" is an intrinsic MATLAB function. The signature of the
function found in file "filename" does not match the known signature for this function:
known number of inputs = quant1,found number of inputs = quant2
known number of outputs = quant1found number of outputs = quant2
known varargin used = quant1,found varargin used = quant2
known varargout used = quant1,found varargout used = quant2
known nargout used = quant1,found nargout used = quant2.
(builtin_signature_mismatch) When compiling an M-file that is contained in
The MathWorks libraries, the number of inputs/outputs and the signatures to
the function must match exactly.
Warning: The file filename was repeated on the Compiler command line. (repeated_file)
This warning occurs when the same filename appears more than once on the
compiler command line. For example,
mcc -x sample.m sample.m % will generate the warning
B-17
B Error and Warning Messages
Warning: The name of a shared library should begin with the letters "lib". "libraryname"
doesn’t. (missing_lib_sentinel) This warning is generated if the name of the
specified library does not begin with the letters “lib”. This warning is specific
to UNIX and does not occur on Windows. For example,
mcc -t -W lib:liba -T link:lib a0 a1 % no warning
mcc -t -W lib:a -T link:lib a0 a1 % will generate a warning
Warning: The option optionname is ignored in modename mode (specify -? for help).
(switch_ignored) Modename = 1.2 or 2.0. Certain options only have meaning in
one or the other mode. For example, if you use the -e option, you can’t use the
-V2.0 option. For more information about Compiler options, see the section,
“MATLAB Compiler Option Flags,” in Chapter 7.
Warning: The specified private directory is not unique. Both "directoryname1" and
"directoryname2" are found on the path for this private directory.
(duplicate_private_directories) The Compiler cannot distinguish which private
function to use. For more information, see “Compiling Private and Method
Functions” in Chapter 5.
B-18
Run-Time Errors
Run-Time Errors
Note The error messages described in this section are generated by the
Compiler into the code exactly as they are written, but are not the only source
of run-time errors. You also can receive run-time errors can from the C/C++
Math Libraries; these errors are not documented in this book. Math Library
errors do not include the source file and line number information. If you
receive such an error and are not certain if it is coming from the C/C++ Math
Libraries or your M-code, compile with the -A debugline:on option to get
additional information about which part of the M source code is causing the
error. For more information about -A (the annotation option), see “Code
Generation Options” in Chapter 7.
Run-time Error: File: filename Line: # Column: # The call to function "functionname" that
appeared on this line was not a known function at compile time. The function was not
found at compile time.
Run-time Error: File: filename Line: # Column: # The call to function "functionname" on this line
passed quantity1 inputs and the function is declared with quantity2. There is an
inconsistency between the formal and actual number of inputs to a function.
Run-time Error: File: filename Line: # Column: # The call to function "functionname" on this line
requested quantity1 outputs and the function is declared with quantity2. There is an
inconsistency between the formal and actual number of outputs from a
function.
Run-time Error: File: filename Line: # Column: # The clear statement did not specifically list the
names of variables to be cleared as constant strings. Use one of the forms of the clear
command that contains the names of the variables to be cleared, for example,
clear name.
Run-time Error: File: filename Line: # Column: # The Compiler does not support EVAL or INPUT
functions. Currently, these are unsupported functions.
Run-time Error: File: filename Line: # Column: # The function "functionname" was called with
more than the declared number of inputs (quantity1). There is an inconsistency
between the declared number of formal inputs and the actual number of inputs.
B-19
B Error and Warning Messages
Run-time Error: File: filename Line: # Column: # The function "functionname" was called with
more than the declared number of outputs (quantity1). There is an inconsistency
between the declared number of formal outputs and the actual number of
outputs.
Run-time Error: File: filename Line: # Column: # The load statement did not specifically list the
names of variables to be loaded as constant strings. Use one of the forms of the load
command that contains the names of the variables to be loaded, for example,
load filename num value.
Run-time Error: File: filename Line: # Column: # The save statement did not specifically list the
names of variables to be saved as constant strings. Use one of the forms of the save
command that contains the names of the variables to be saved, for example,
save testdata num value.
B-20
Index
Symbols
#line directives 5-36 bcc53opts.bat 2-17
%#external 7-5 bcc54opts.bat 2-17
%#function 7-6 bcc55opts.bat 2-17
%#mex 7-7 bccopts.bat 2-17
%#mex pragma 7-7 Borland compiler 2-15
.cshrc 4-12 environment variable 2-27
.DEF file 4-22 bundling compiler options
-B option flag 7-43
A
-A option flag 7-38 C
add-in -c option flag 7-43
MATLAB for Visual Studio 2-23, 4-24 C
adding directory to path compilers
-I option flag 7-43 supported on PCs 2-15
algorithm hiding 1-14 supported on UNIX 2-6
annotating generating 7-43
-A option flag 7-38 interfacing to M-code 5-40
code 5-34, 7-38 shared library wrapper 5-23
output 7-38 C++
ANSI compiler compilers
installing on Microsoft Windows 2-18 supported on PCs 2-15
installing on UNIX 2-8 supported on UNIX 2-6
application interfacing to M-code 5-40
POSIX main 5-21 library wrapper 5-26
application coding with required features
M-files and C/C++ files 4-37 templates 4-7
M-files only 4-31 changing compiler on PC 2-21
array power function 7-22 changing license file
-Y option flag 7-45
code
B controlling #line directives 5-36
-B option flag 7-43 controlling comments in 5-34
-B pcode option flag 7-38 controlling run-time error information 5-38
-B sgl option flag 7-37 hiding 1-14
-B sglcpp option flag 7-38 porting 5-27
I-1
Index
D F
-d option flag 7-43 -F option flag 5-29, 7-40
debugging -f option flag 7-46
-G option flag 7-46 Fcn block 3-8
line numbers of errors 7-41 feval 5-42, 7-6
debugging symbol information 7-40 interface function 5-11, 5-15
debugline setting 5-38 feval pragma 7-5, 7-6
Digital Fortran 2-27
I-2
Index
file G
license.dat 2-7, 2-18 -G option flag 7-46
mccpath 7-33 -g option flag 7-40
mlib 5-23, 5-25 gasket.m 3-3
wrapper 1-7 gcc compiler 2-6
for. See loops. generated Compiler files 5-4
formatting code 5-29 generating P-code 7-38
-F option flag 7-40
listing all options 5-29
setting indentation 5-31 H
setting page width 5-29 -h option flag 7-43
Fortran 2-27 header file
full pathnames C example 5-8
handling 7-34 C++ example 5-9
%#function 5-42, 7-6 helper functions
%#mex 7-7 -h option 7-43
function in stand-alone applications 4-36
calling from M-code 5-40 hiding code 1-14
comparison to scripts 3-11
compiling
method 5-6 I
private 5-6 -I option flag 7-43
I-3
Index
I-4
Index
I-5
Index
I-6
Index
I-7
Index
I-8
Index
I-9
Index
X
-x option flag 7-37
Y
-Y option flag 7-45
-y option flag 3-9, 7-42
Z
-z option flag 7-46
I-10