Documente Academic
Documente Profesional
Documente Cultură
Users Guide
Version 3
Web Newsgroup Technical support Product enhancement suggestions Bug reports Documentation error reports Order status, license renewals, passcodes Sales, pricing, and general information Phone Fax Mail
508-647-7000 508-647-7001 The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site. MATLAB Compiler Users Guide COPYRIGHT 1995 - 2002 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used or copied only under the terms of the license agreement. No part of this manual may be photocopied or reproduced in any form without prior written consent from The MathWorks, Inc. FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by or for the federal government of the United States. By accepting delivery of the Program, the government hereby agrees that this software qualifies as "commercial" computer software within the meaning of FAR Part 12.212, DFARS Part 227.7202-1, DFARS Part 227.7202-3, DFARS Part 252.227-7013, and DFARS Part 252.227-7014. The terms and conditions of The MathWorks, Inc. Software License Agreement shall pertain to the governments use and disclosure of the Program and Documentation, and shall supersede any conflicting contractual terms or conditions. If this license fails to meet the governments minimum needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Documentation, unused, to MathWorks. MATLAB, Simulink, Stateflow, Handle Graphics, and Real-Time Workshop are registered trademarks, and TargetBox is a trademark of The MathWorks, Inc. Other product or brand names are trademarks or registered trademarks of their respective holders.
Printing History: September 1995 March 1997 January 1998 January 1999 September 2000 October 2001 July 2002
First printing Second printing Third printing Fourth printing Fifth printing Online only Sixth printing
Revised for Version 1.2 Revised for Version 2.0 (Release 11) Revised for Version 2.1 (Release 12) Revised for Version 2.3 Revised for Version 3.0 (Release 13)
Contents
Preface
1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 Before You Begin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 New Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Compiler 3.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Compiler 2.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Compiler 2.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Compiler Licensing Changes . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-4 1-4 1-4 1-5 1-7
Uses of the Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9 Creating MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9 Creating Stand-Alone Applications . . . . . . . . . . . . . . . . . . . . . 1-11 The MATLAB Compiler Family . . . . . . . . . . . . . . . . . . . . . . . . 1-14 Why Compile M-Files? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16 Stand-Alone Applications and Libraries . . . . . . . . . . . . . . . . . 1-16 Excel Plug-Ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16
COM Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16 Hiding Proprietary Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . 1-16 Upgrading from Previous Versions of the Compiler . . . . . 1-17 Upgrading from MATLAB Compiler 2.0/2.1/2.2/2.3 . . . . . . . . . 1-17 Upgrading from MATLAB Compiler 1.0/1.1 . . . . . . . . . . . . . . . 1-17 Limitations and Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Stand-Alone Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Fixing Callback Problems: Missing Functions . . . . . . . . . . . . .
1-18 1-18 1-19 1-20
2
System Configuration for MEX-Files . . . . . . . . . . . . . . . . . . . . 2-2 UNIX Workstation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4 System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6 mex Verification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7 MATLAB Compiler Verification . . . . . . . . . . . . . . . . . . . . . . . . 2-11 Microsoft Windows on PCs . . . . . . . . . . . . . . . . . . . . . . . . . . . . System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . mex Verification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Compiler Verification . . . . . . . . . . . . . . . . . . . . . . . .
2-13 2-13 2-17 2-19 2-23
ii
Contents
3
A Simple Example The Sierpinski Gasket . . . . . . . . . . . . . 3-2 Compiling the M-File into a MEX-File . . . . . . . . . . . . . . . . . . . . 3-3 Invoking the MEX-File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4 Compiler Options and Macros . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6 Generating Simulink S-Functions . . . . . . . . . . . . . . . . . . . . . . 3-7 Simulink Specific Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7 Specifying S-Function Characteristics . . . . . . . . . . . . . . . . . . . . 3-8 Converting Script M-Files to Function M-Files . . . . . . . . . . 3-10
Stand-Alone Applications
4
Differences Between MEX-Files and Stand-Alone Applications . . . . . . . . . . . . . . . . . . . . . . . . . 4-2 Stand-Alone C Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2 Stand-Alone C++ Applications . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3 Building Stand-Alone C/C++ Applications . . . . . . . . . . . . . . . 4-4 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6 Building Stand-Alone Applications on UNIX . . . . . . . . . . . . . 4-7 Configuring for C or C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7 Preparing to Compile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-8 Verifying mbuild . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11 Verifying the MATLAB Compiler . . . . . . . . . . . . . . . . . . . . . . . 4-12 About the mbuild Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-13 Packaging UNIX Applications . . . . . . . . . . . . . . . . . . . . . . . . . . 4-13
iii
Building Stand-Alone Applications on PCs . . . . . . . . . . . . . Configuring for C or C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Preparing to Compile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Verifying mbuild . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Verifying the MATLAB Compiler . . . . . . . . . . . . . . . . . . . . . . . About the mbuild Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Using an Integrated Development Environment . . . . . . . . . . . Packaging Windows Applications for Distribution . . . . . . . . . Distributing Stand-Alone Applications . . . . . . . . . . . . . . . . . Packaging the MATLAB Run-Time Libraries . . . . . . . . . . . . . Installing Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . Problem Starting Stand-Alone Application . . . . . . . . . . . . . . .
4-15 4-15 4-16 4-22 4-23 4-23 4-23 4-26 4-27 4-27 4-27 4-28
Building Shared Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-30 Building COM Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-31 Building Excel Plug-Ins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-32 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-33 Troubleshooting mbuild . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-33 Troubleshooting the Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . 4-35 Coding with M-Files Only . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-36 Alternative Ways of Compiling M-Files . . . . . . . . . . . . . . . . . 4-40 Compiling MATLAB Provided M-Files Separately . . . . . . . . . 4-40 Compiling mrank.m and rank.m as Helper Functions . . . . . . 4-41 Mixing M-Files and C or C++ . . . . . . . . . . . . . . . . . . . . . . . . . . 4-42 Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-42 Advanced C Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-47
iv
Contents
5
Code Generation Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2 Example M-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2 Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3 Compiling Private and Method Functions . . . . . . . . . . . . . . . 5-5 The Generated Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8 C Header File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8 C++ Header File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9 Internal Interface Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11 C Interface Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11 C++ Interface Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16 Supported Executable Types . . . . . . . . . . . . . . . . . . . . . . . . . . Generating Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . MEX-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Main Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Simulink S-Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C Shared Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C++ Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . COM Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Porting Generated Code to a Different Platform . . . . . . . . . . . Formatting Compiler-Generated Code . . . . . . . . . . . . . . . . . Listing All Formatting Options . . . . . . . . . . . . . . . . . . . . . . . . . Setting Page Width . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Setting Indentation Spacing . . . . . . . . . . . . . . . . . . . . . . . . . . . Including M-File Information in Compiler Output . . . . . . Controlling Comments in Output Code . . . . . . . . . . . . . . . . . . Controlling #line Directives in Output Code . . . . . . . . . . . . . . Controlling Information in Run-Time Errors . . . . . . . . . . . . . .
5-21 5-21 5-22 5-22 5-24 5-24 5-25 5-28 5-29 5-34 5-35 5-35 5-35 5-37 5-40 5-40 5-42 5-44
Interfacing M-Code to C/C++ Code . . . . . . . . . . . . . . . . . . . . . 5-46 C Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-46 Using Pragmas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-48
Optimizing Performance
6
Optimization Bundles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2 Optimizing Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Scalar Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Nonscalar Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Scalars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6-4 6-4 6-4 6-5
Optimizing Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6 Simple Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6 Loop Simplification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6 Optimizing Conditionals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9 Optimizing MATLAB Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10 Scalars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10 Scalar Doubles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10
Reference
7
Functions By Category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Pragmas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Compiler Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Command Line Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
7-2 7-2 7-2 7-2
vi
Contents
A
Common Uses of the Compiler . . . . . . . . . . . . . . . . . . . . . . . . . A-2 mcc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4
B
Compile-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-2 Warning Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-11 Run-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-18
vii
viii Contents
Preface
This chapter provides information about this documentation set. The sections are as follows. Related Products (p. x) Using this Guide (p. xi) Typographical Conventions (p. xii) MathWorks products related to the Compiler An overview of this book Typographical conventions used in this book
Preface
Related Products
The MATLAB Compiler automatically converts MATLAB M-files to C and C++ code. The MATLAB Compiler includes the MATLAB C/C++ Math and Graphics Libraries, which let you automatically convert your MATLAB applications to C and C++ code for stand-alone applications. The MathWorks provides several products that are especially relevant to the MATLAB Compiler. For more information about any of these products, see either The online documentation for that product The products section of the MathWorks Web site, www.mathworks.com.
Product
Description
MATLAB COM Builder MATLAB Excel Builder MATLAB Runtime Server MATLAB Web Server
Creating COM components from MATLAB M-files Creating MATLAB based add-ins for Excel Deploy run-time versions of MATLAB applications Use MATLAB with HTML Web applications
xi
Preface
Typographical Conventions
This manual uses some or all of these conventions.
Item Convention Monospace font Example
Example code
Function names, syntax, filenames, directory/folder names, user input, items in drop-down lists Buttons and keys Literal strings (in syntax descriptions in reference chapters) Mathematical expressions MATLAB output
Monospace font
The cos function finds the cosine of each array element. Syntax line example is
MLGetVar ML_var_name
Italics for variables Standard text font for functions, operators, and constants
Monospace font
Menu and dialog box titles New terms and for emphasis Omitted input arguments
Italics (...) ellipsis denotes all of the input/output arguments from preceding syntaxes.
Monospace italics
sysc = d2c(sysd,'method')
xii
1
Introducing the MATLAB Compiler
This chapter describes the MATLAB Compiler and its uses. It also includes new features, upgrading information, and limitations and restrictions that you should know. Introduction (p. 1-2) New Features (p. 1-4) Uses of the Compiler (p. 1-9) The MATLAB Compiler Family (p. 1-14) Why Compile M-Files? (p. 1-16) Upgrading from Previous Versions of the Compiler (p. 1-17) Limitations and Restrictions (p. 1-18) A brief overview Features added in this and previous releases High-level descriptions of what the Compiler can do Pictorial view of the Compilers output Reasons to compile M-files Compatibility issues Restrictions regarding what can be compiled
Introduction
This book describes Version 3.0 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: C source code for building MEX-files. C or C++ source code for combining with other modules to form stand-alone applications. Stand-alone applications do not require MATLAB at run-time; they can run even if MATLAB is not installed on the end-users system. C code S-functions for use with Simulink. C shared libraries (dynamically linked libraries, or DLLs, on Microsoft Windows) and C++ static libraries. These can be used without MATLAB on the end-users system. Excel compatible plug-ins COM (Component Object Model) objects. This chapter takes a closer look at these categories of C and C++ source code and explains the value of compiled code.
Note MATLAB Compiler 3.0 includes the MATLAB C/C++ Math Library and the MATLAB C/C++ Graphics Library. Installing the MATLAB Compiler automatically installs the C/C++ Math and Graphics Libraries.
1-2
Introduction
Note The phrase MATLAB interpreter refers to the application that accepts MATLAB commands, executes M-files and MEX-files, and behaves as described in the Using MATLAB documentation. When you use MATLAB, you are using the MATLAB interpreter. The phrase MATLAB Compiler refers to this product, which translates M-files to C or C++ source code and its associated libraries. 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-3
New Features
MATLAB Compiler 3.0
The MATLAB Compiler now includes the MATLAB C/C++ Math and Graphics Libraries. Note As the MATLAB Compiler evolves, it will support additional standard platform interfaces such as COM, Java, and CORBA. Consequently, the requirement of developing code specifically for the MATLAB C/C++ Math Library will diminish. Once this happens, the Math Library will no longer support code written directly for the Library. The Compiler will continue to use the MATLAB C/C++ Math Library as it currently does.
A new optimization is available that allows the Compiler to use simpler types for variables at run-time, when possible. For more information about this optimization, see Chapter 6, Optimizing Performance. The MATLAB Compiler allows you to create COM components from MATLAB M-files. Note To create COM components with the MATLAB Compiler, you must have the MATLAB COM Builder product installed on your system.
1-4
New Features
The new option, -b, causes the Compiler to generate a Visual Basic (.bas) file that contains the Microsoft Excel Formula Function interface to a Compiler-generated COM object. The new option, -i, causes the Compiler to include only the M-files that are specified on the command line as exported interfaces.
Note To create Microsoft Excel components with the MATLAB Compiler, you must have the MATLAB Excel Builder product installed on your system.
Optimizations
The MATLAB Compiler 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
1-5
conditional operators when both operands are known to be integer scalars. For more information on these optimizations, see Chapter 6, Optimizing Performance.
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 files 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-26.
1-6
New Features
Note As of Compiler 2.1, Compiler 1.2 is no longer available due to the evolution of internal data structures. The -V1.2 option is no longer supported, along with any options recognized by Compiler 1.2.
1-7
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-8
Note MEX-files generated by the MATLAB Compiler are not backward compatible.
Creating MEX-Files
The MATLAB Compiler, when invoked with the -x macro option, produces a MEX-file from M-files. The Compiler
1 Translates your M code to C code. 2 Generates a MEX wrapper. 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). Figure 1-1, Developing MEX-Files, illustrates the process of producing a MEX-file. The MATLAB interpreter dynamically loads MEX-files as they are needed.
1-9
M-File
mcc -x
Shaded block is user-written code. C version of M code C MEX-File Wrapper Shadowed blocks are MathWorks tools. Unshaded blocks are MATLAB Compiler-generated code. Dotted block is C/C++ compiler-generated executable.
mex
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 in the MATLAB documentation 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-10
1-11
mcc -m
this part.
C version of M code
C File Wrapper
Shadowed blocks are tools. Unshaded blocks are MATLAB Compiler-generated code. Dotted blocks are C/C++ compiler-generated executables.
C Compiler
Object Files
MATLAB M-File Math Library MATLAB Math Built-In Library ANSI C Library
MATLAB API Library MATLAB Utility Library MATLAB C/C++ Graphics Library
Linker
Stand-Alone C Application
1-12
See Chapter 4, Stand-Alone Applications for complete details regarding stand-alone applications. Figure 1-2, Developing a Typical Stand-Alone C Application, illustrates the process of developing a typical stand-alone C application. Use the same basic process for developing stand-alone C++ applications, but use the -p option instead of the -m option with the MATLAB Compiler and a C++ compiler instead of a C 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. Chapter 7, Reference, includes a complete description of the Compiler options in the mcc section. Throughout this book you will see numerous examples of how these options are used with the Compiler to perform various tasks.
1-13
MATLAB Compiler
C++ Code 1
2 3 4 5 5 3
Target Types
Simulink C MEX-File
1-14
The Compiler takes your M-file(s) and can generate C or C++ code. It can also generate a wrapper file depending on your specified target. This table shows the wrapper files the Compiler can generate, their associated targets, and the corresponding -W option (wrapper).
Table 1-1: Compiler Wrappers and Targets Wrapper File Target -W Setting -W main
Main
Stand-alone C or C++ program MATLAB C MEX-file C shared library or C++ static library Simulink C MEX-file COM object Excel Plug-in
MEX Library
-W mex
-W lib:libname
-W simulink
Each numbered node in Figure 1-3, MATLAB Compiler Uses, indicates a combination of C/C++ code and a wrapper that generates a specific target type. The file(s) formed by combining the C/C++ code (denoted by User C/C++ Code) and the wrapper are then passed to the C/C++ compiler, which combines them with any user-defined C/C++ programs, and eventually links them against the appropriate libraries. The end result of this sequence is the target as described in the table above.
1-15
Excel Plug-Ins
With the optional MATLAB Excel Builder, you can automatically generate a Visual Basic Application file (.bas) and a plug-in DLL from your MATLAB model that can be imported into Excel as a stand-alone function.
COM Components
With the optional MATLAB COM Builder, you can create COM components that can be used in any application that works with COM objects.
1-16
1-17
M-files that use exist with two input arguments, for example:
exist('foo','var')
The single variable form works for filenames and functions only. M-files that dynamically name variables to be loaded or saved. This example is disallowed by the Compiler:
x= 'f'; load('foo.mat',x);
The Compiler cannot compile built-in MATLAB functions (functions such as eig have no M-file, so they cant be compiled). Note, however, that most of these functions are available to you because they are in the MATLAB Math Built-in Library (libmatlb). In addition, the Compiler does not honor conditional global and persistent declarations. It treats global and persistent as declarations. For example:
1-18
Stand-Alone Applications
The restrictions and limitations noted in the previous section also apply to stand-alone applications. The functions in Table 1-2, Unsupported Functions in Stand-Alone Mode, are supported in MEX-mode, but are not supported in stand-alone mode.
Note 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.
Table 1-2: Unsupported Functions in Stand-Alone Mode add_block callstats dbcont dbstatus dbup echo evalin get_param hregister isjava add_line close_system dbdown dbstep delete_block edt fields hcreate inferiorto isruntime applescript cputime dbquit dbstop delete_line errorstat fschange help inmem java assignin dbclear dbstack dbtype diary errortrap functionscalled home isglobal javaArray
1-19
Table 1-2: Unsupported Functions in Stand-Alone Mode (Continued) javaMethod lookfor mislocked new_system rehash simget superiorto vms whos javaObject macprint mlock open_system runtime simset system_dependent what keyboard mactools more pack set_param sldebug trmginput which linmod methods munlock pfile sim str2func type who
Symptom
Your application runs, but an interactive user interface element, such as a push button, is unresponsive. When you close the application, the graphics library issues this error message.
An error occurred in the callback : change_colormap The error message caught was : Reference to unknown function change_colormap from FEVAL in stand-alone mode.
Workaround
To eliminate this error, create a list of all the functions that are specified only in callback strings and pass this list to the %#function pragma. (See Finding Missing Functions in an M-File on page 1-21 for hints about finding functions
1-20
in callback strings.) The Compiler processes any function listed in a %#function pragma. For example, the call to the change_colormap function in the sample application, my_test, illustrates this problem. To make sure the Compiler processes the change_colormap M-file, list the function name in the %#function pragma:
function my_test() % Graphics library callback test application %#function change_colormap peaks; p_btn = uicontrol(gcf,... 'style', 'pushbutton',... 'Position',[10 10 133 25 ],... 'String', 'Make Black & White',... 'CallBack','change_colormap');
Note Instead of using the %#function pragma, you can specify the name of the missing M-file on the Compiler command line.
1-21
1-22
2
Installation and Configuration
This chapter describes the system requirements for the MATLAB Compiler and installation and configuration information. It includes information for both MATLAB Compiler platforms UNIX and Microsoft Windows. When you install your ANSI C or C++ compiler, you may be required to provide specific configuration details regarding your system. This chapter contains information for each platform that can help you during this phase of the installation process. The sections, Things to Be Aware of, provide this information for each platform. System Configuration for MEX-Files (p. 2-2) UNIX Workstation (p. 2-4) Microsoft Windows on PCs (p. 2-13) Troubleshooting (p. 2-25) Steps to create MEX-files Configuration on UNIX systems Configuration on PCs Dealing with installation and configuration problems
Note If you encounter problems relating to the installation or use of your ANSI C or C++ compiler, consult the documentation or customer support organization of your C or C++ compiler vendor.
3 Verify that mex can generate MEX-files. 4 Verify that the MATLAB Compiler can generate MEX-files from the
MATLAB command line and from the UNIX or DOS command line. Figure 2-1, MATLAB Compiler Installation Sequence for Creating MEX-Files, 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.
Note This flowchart assumes that MATLAB is properly installed on your system.
2-2
Start
No
Yes
Verify mex
Does the MATLAB command mex yprime.c generate proper MEX-file ? Yes 2
No
1
Verify MATLAB Compiler can generate MEX-files from MATLAB/DOS/ UNIX command line
No
Stop
2-3
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.5 (Release 13) 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. Table 2-1, Requirements for Creating UNIX Applications, shows the requirements for creating UNIX applications with the MATLAB Compiler.
Table 2-1: Requirements for Creating UNIX Applications To create... You need...
ANSI C compiler MATLAB Compiler ANSI C compiler MATLAB Compiler C++ compiler MATLAB Compiler
Note Although the MATLAB Compiler supports the creation of stand-alone C++ applications, it does not support the creation of C++ MEX-files.
2-4
UNIX Workstation
Note For a list of all the compilers supported by MATLAB, see the MathWorks Technical Support Departments Technical Notes at
http://www.mathworks.com/support/tech-notes/1600/1601.shtml
Known Compiler Limitations. There are several known restrictions regarding the use of supported compilers:
The SGI C compiler does not handle denormalized floating-point values correctly. Denormalized floating-point numbers are numbers that are greater than 0 and less than the value of DBL_MIN in the compilers float.h file. Due to a limitation of the GNU C++ compiler (g++) on Linux, try catch end blocks do not work. The -A debugline:on option does not work on the GNU C++ compiler (g++) on Linux because it uses try catch end. Some UNIX compilers produce warnings that suggest additional optimizations can be performed that might result in faster code. For example, on IBM RS/6000 systems you may see a warning message similar to
1500-030: (I) INFORMATION: Miofun_private_imgifinfo: Additional optimization may be attained by recompiling and specifying MAXMEM option with a value greater than 2048.
See your vendor compiler documentation for more information on how to improve optimization. Normally, this involves changing compiler options. Use CFLAGS= in your mbuildopts file. Note This compiler warning is benign and will have no harmful effect on your code.
2-5
shows the preconfigured options files that are included with MATLAB for UNIX.
Compiler Options File mexopts.sh gccopts.sh
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 workstations, follow the instructions in the MATLAB Installation Guide for the UNIX platform. 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): Via the Web at www.mathworks.com. On the MathWorks home page, click on the MATLAB Access option, log in to the Access home page, and follow the instructions. Via e-mail at service@mathworks.com
2-6
UNIX Workstation
Note On some UNIX platforms, a C or C++ compiler may already be installed. Check with your system administrator for more information.
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
Determine which C or C++ compiler is installed on your system. Determine the path to your C or C++ compiler.
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 systems compiler as your default compiler for creating C MEX-files.
2-7
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-9. 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 Using the 'mex -setup' command selects an options file that is placed in ~/.matlab/R13 and used by default for 'mex'. An options file in the current working directory or specified on the command line overrides the default options file in ~/.matlab/R13. 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 'mex -f' command (see 'mex -help' for more information). The options files available for mex are: 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 doesnt 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-8
UNIX Workstation
Note The setup option creates a user-specific, matlab directory in your individual home directory and copies the appropriate options file to the directory. (If the directory already exists, a new one is not created.) This matlab directory is used for your individual options files only; each user can have his or her own default options files (other MATLAB products may place options files in this directory). Do not confuse these user-specific matlab directories with the system matlab directory, where MATLAB is installed.
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 compilers options file to your specific version.
Temporarily Changing the Compiler. To temporarily change your C or C++ compiler,
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-9
On UNIX, MEX-files are created with platform-specific extensions, as shown in Table 2-2, MEX-File Extensions for UNIX.
Table 2-2: MEX-File Extensions for UNIX Platform MEX-File Extension mexaxp mexhp7 mexhpux mexrs6 mexglx mexsg mexsol
Dec/Compaq Alpha HP 9000 PA-RISC HP-UX IBM RS/6000 Linux SGI Solaris
The <matlab>/extern/examples/mex directory contains C source code for the example yprime.c. After you copy the source file (yprime.c) to a local directory and cd to that directory, enter at the MATLAB prompt
mex yprime.c
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
If you encounter problems generating the MEX-file or getting the correct results, refer to External Interfaces/API in the MATLAB documentation for additional information about MEX-files.
2-10
UNIX Workstation
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 Compilers 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.
Copy invhilb.m from the <matlab>/toolbox/matlab/elmat directory to a local directory and then type the following at the UNIX prompt:
mcc -x invhilb
2-11
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-12
System Requirements
You cannot install the MATLAB Compiler unless MATLAB 6.5 (Release 13) 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. Table 2-3, Requirements for Creating PC Applications, shows the requirements for creating PC applications with the MATLAB Compiler.
Table 2-3: Requirements for Creating PC Applications To create... You need...
ANSI C compiler (see following note) MATLAB Compiler ANSI C compiler (see following note) MATLAB Compiler C++ compiler MATLAB Compiler
Note MATLAB includes an ANSI C compiler (Lcc) that is suitable for use with the MATLAB Compiler.
Note Although the MATLAB Compiler supports the creation of stand-alone C++ applications, it does not support the creation of C++ MEX-files.
2-13
Note For a list of all the compilers supported by MATLAB, see the MathWorks Technical Support Departments Technical Notes at
http://www.mathworks.com/support/tech-notes/1600/1601.shtml
Applications generated by the MATLAB Compiler are 32-bit applications and only run on any MATLAB-supported Microsoft Windows systems. For a complete list of supported Windows platforms, see http://www.mathworks.com/products/system.shtml/Windows.
2-14
Known Compiler Limitations. There are several known restrictions regarding the use of supported compilers:
Some compilers, e.g., Watcom, do not handle denormalized floating-point values correctly. Denormalized floating-point numbers are numbers that are greater than 0 and less than the value of DBL_MIN in your compilers float.h file. The MATLAB Compiler 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-15
Lcc C, Version 2.4 (included with MATLAB) Microsoft Visual C/C++, Version 5.0 Microsoft Visual C/C++, Version 6.0 Microsoft Visual C/C++, Version 7.0 Watcom C/C++, Version 10.6 Watcom C/C++, Version 11.0
msvc50opts.bat msvc60opts.bat msvc70opts.bat watcopts.bat (supported for mex only, not for mbuild) wat11copts.bat (supported for mex only, not for mbuild) bcc53opts.bat bcc54opts.bat bcc55opts.bat bcc56opts.bat
Borland C++ Builder 3 Borland C++ Builder 4 Borland C++ Builder 5 Borland C++ Builder 6
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-16
created during the -setup process, in a subdirectory of your user profile directory, named Application Data\MathWorks\MATLAB\R13. Under Windows with user profiles enabled, your user profile directory is %windir%\Profiles\username. Under Windows with user profiles disabled, your user profile directory is %windir%. You can determine whether or not user profiles are enabled by using the Passwords control panel.
Installation
MATLAB Compiler
To install the MATLAB Compiler on a PC, follow the instructions in the Installation Guide for Windows. 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: Via the Web at www.mathworks.com. On the MathWorks home page, click on Support, then click on the Access Login, and follow the instructions. Via e-mail at service@mathworks.com
2-17
Things to Be Aware of
This table provides information regarding the installation and configuration of a C/C++ compiler on your system.
Description Comment
Installation options
We recommend that you do a full installation of your compiler. If you do a partial installation, you may omit a component that the MATLAB Compiler relies on. For the purposes of the MATLAB Compiler, it is not necessary to install debugger (DBG) files. However, you may need them for other purposes. This is not required. This is not required. This is not required. Make sure you select all relevant options for running your compiler from the command line. If your installer gives you the option of updating the registry, you should do it. If you need to change the location where this compiler is installed, you must change the location of the Common directory. Do not change the location of the VC98 directory from its default setting.
Microsoft Foundation Classes (MFC) 16-bit DLL/executables ActiveX Running from the command line Updating the registry Installing Microsoft Visual C/C++ Version 6.0
2-18
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-22.
Note On Windows 98 systems, if you get the error, out of environment space, see Out of Environment Space Running mex or mbuild on page 2-25 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-19
[1] : Borland compiler in T:\Borland\BC.500 [2] : WATCOM compiler in T:\watcom\c.106 [0] : None Please select a compiler. This compiler will become the default:
Select the desired compiler by entering its number and pressing Return. You are then asked to verify the information.
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 Please choose your compiler for building external interface (MEX) files. Would you like mex to locate installed compilers [y]/n? n Select a compiler: [1] Borland C++Builder version 6.0 [2] Borland C++Builder version 5.0 [3] Borland C++Builder version 4.0 [4] Borland C++Builder version 3.0 [5] Borland C/C++ version 5.02 [6] Borland C/C++ version 5.0 [7] Borland C/C++ (free command line tools) version 5.5 [8] Compaq Visual Fortran version 6.6 [9] Compaq Visual Fortran version 6.1 [10] Digital Visual Fortran version 6.0 [11] Digital Visual Fortran version 5.0 [12] Lcc C version 2.4 [13] Microsoft Visual C/C++ version 7.0 [14] Microsoft Visual C/C++ version 6.0
2-20
[15] Microsoft Visual C/C++ version 5.0 [16] WATCOM C/C++ version 11 [17] WATCOM C/C++ version 10.6 [0] None Compiler: 14 Your machine has a Microsoft Visual C/C++ compiler located at D:\Applications\Microsoft Visual Studio. Do you want to use this compiler [y]/n? y Please verify your choices: Compiler: Microsoft Visual C/C++ 6.0 Location: D:\Applications\Microsoft Visual Studio Are these correct?([y]/n): y The default options file: "C:\WINNT\Profiles\username \Application Data\MathWorks\MATLAB\R13\mexopts.bat" is being updated... Installing the MATLAB Visual Studio add-in ... 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.
2-21
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. After completing this process, the mex script will use the new options file everytime with your modified settings.
Temporarily Changing the Compiler. To temporarily change your C or C++ compiler,
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
This should create the yprime.dll MEX-file. MEX-files created on Windows always have the extension dll. You can now call yprime as if it were an M-function. For example,
yprime(1,1:4) ans = 2.0000 8.9685
4.0000
-1.0947
If you encounter problems generating the MEX-file or getting the correct results, refer to External Interfaces/API in the MATLAB documentation for additional information about MEX-files.
2-22
mex -setup and select Microsoft Visual C/C++ version 5 or 6. For more
information about the add-in, see Using an Integrated Development Environment on page 4-23.
Note The MATLAB add-in for Visual Studio does not currently work with Microsoft Visual C/C++, Version 7.0.
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 Compilers ability to make MEX-files. If you want to create stand-alone applications or DLLs, refer to Chapter 4, Stand-Alone Applications.
2-23
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.
Copy invhilb.m from the <matlab>\toolbox\matlab\elmat directory to a local directory and then type the following at the DOS prompt.
mcc -x invhilb
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-24
Troubleshooting
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 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
On Windows Me systems, if you encounter this problem and are using the MATLAB add-in for Visual Studio, follow the procedure in Configuring on Windows 98 and Windows Me Systems on page 4-25.
Non-ANSI C Compiler on UNIX. A common configuration problem in creating C MEX-files on UNIX involves using a non-ANSI C compiler. You must use an ANSI C compiler. 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. Segmentation Violation or Bus Error. If your MEX-file causes a segmentation violation or bus error, there is most likely a problem with the MATLAB Compiler. Contact Technical Support at The MathWorks at support@mathworks.com. 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 support@mathworks.com.
2-25
mex Works from Shell But Not from MATLAB (UNIX). If the command mex -x yprime.c
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:
BORLAND for Borland C++ Compiler, Version 5.3 WATCOM for the Watcom C/C++ Compiler MSVCDIR for Microsoft Visual C/C++, Version 5.0, 6.0, or 7.0 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 reenable your antivirus software.
Verification of mex Fails. If none of the previous solutions addresses your difficulty with mex, contact Technical Support at The MathWorks at support@mathworks.com.
2-26
Troubleshooting
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.
If you have a licensing problem, contact The MathWorks. A list of contacts at The MathWorks is provided at the beginning of this manual.
MATLAB Compiler Does Not Generate MEX-File. If you experience other problems with the MATLAB Compiler, contact Technical Support at The MathWorks at support@mathworks.com.
2-27
2-28
3
Working with MEX-Files
This chapter gets you started compiling M-files with the MATLAB Compiler. A Simple Example The Sierpinski Gasket (p. 3-2) Compiler Options and Macros (p. 3-6) Generating Simulink S-Functions (p. 3-7) Converting Script M-Files to Function M-Files (p. 3-10) Creating a MEX-file from an M-file Overview of options and macros Generating Simulink C MEX S-functions Converting scripts to functions
theImage = zeros(1000,1000); corners = [866 1;1 500;866 1000]; startPoint = [866 1]; theRand = rand(numPoints,1); theRand = ceil(theRand*3); for i=1:numPoints startPoint = floor((corners(theRand(i),:)+startPoint)/2); theImage(startPoint(1),startPoint(2)) = 1; end
3-2
The curve can be graphed in many ways. Sierpinski's method is 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. To achieve a reasonable approximation of the Sierpinski Gasket, set the number of points to 50,000. To invoke the M-file and compute the coordinates, you can use
x = gasket(50000);
This mcc command generates A file named gasket.c containing MEX-file C source code. A file named gasket.h containing the public information. A file named gasket_mex.c containing the MEX-function interface (MEX wrapper). A MEX-file named gasket.mex. (The actual filename extension of the executable MEX-file varies depending on your platform, e.g., on the PC the file is named gasket.dll.)
mcc automatically invokes mex to create gasket.mex from gasket.c and gasket_mex.c. The mex utility encapsulates the appropriate C compiler and
3-3
This example uses the -x macro option to create the MEX-file. For more information on this Compiler option, see the mcc reference page. For more information on the files that the Compiler generates, see Chapter 5, Controlling Code Generation.
MATLAB runs the MEX-file version (gasket.mex, which is gasket.dll on the PC) 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.
Note To verify that the MEX-file version ran, use the which command
which gasket D:\work\gasket.dll
3-4
Figure 3-1, The Sierpinski Gasket for 50,000 Points, shows the results.
3-5
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 as complete information on all the other available Compiler options, see the mcc reference page.
3-6
For more information about Simulink in general, see the Simulink documentation. For more information about Simulink S-functions, see Writing S-Functions in the Simulink documentation.
Note The MATLAB Compiler option that generates a C language S-function is a capital S (-S).
3-7
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, which is normally available with Simulink S-functions.
3-8
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-9
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] m = magic(sz); t = m .^ 3; disp(t) = % % % houdini(sz) Assign matrix to m. Cube each element of m. 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-10
in the MATLAB workspace. If it is important to have m accessible from the MATLAB workspace, you can change the beginning of the function to
function [m,t] = houdini
3-11
3-12
4
Stand-Alone Applications
This chapter explains how to use the MATLAB Compiler to code and build stand-alone 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, which are detailed in the corresponding sections. Differences Between MEX-Files and Stand-Alone Applications (p. 4-2) Building Stand-Alone C/C++ Applications (p. 4-4) Building Stand-Alone Applications on UNIX (p. 4-7) Building Stand-Alone Applications on PCs (p. 4-15) Distributing Stand-Alone Applications (p. 4-27) Building Shared Libraries (p. 4-30) Building COM Objects (p. 4-31) Building Excel Plug-Ins (p. 4-32) Troubleshooting (p. 4-33) Coding with M-Files Only (p. 4-36) Overview of the differences Steps to create stand-alone C/C++ applications UNIX-specific steps to create stand-alone applications PC-specific steps to create stand-alone applications Packaging applications for users Steps to create C shared libraries Steps to create COM objects Steps to create Excel plug-ins Common problems with mbuild and the MATLAB Compiler Creating stand-alone applications from M-files and MEX-files
Alternative Ways of Compiling M-Files Other ways of compiling M-files (p. 4-40) Mixing M-Files and C or C++ (p. 4-42) Creating applications from M-files and C/C++ code
Stand-Alone Applications
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 the %#mex reference page.
Note The Compiler-generated code cannot invoke Compiler-generated MEX-files. Specify the M-file(s) source instead and the Compiler will compile those into the stand-alone application.
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. 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.
4-2
For more information about distributing a C application, see Distributing Stand-Alone Applications on page 4-27.
Note If you attempt to compile M-files to produce stand-alone applications and you do not have the MATLAB C/C++ Math Library installed, the system will not be able to find the appropriate libraries and the linking will fail. Also, if you do not have the MATLAB C/C++ Graphics Library installed, the MATLAB Compiler will generate run-time errors if the graphics functions are called.
Note On the PC, the MATLAB C++ Math Library is static because the different PC compiler vendors use different C++ name-mangling algorithms.
4-3
Stand-Alone 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
1 Verify that mbuild can create stand-alone applications. 2 Verify that the MATLAB Compiler can link object files with the proper
4-4
Figure 4-1, Sequence for Creating Stand-Alone C/C++ Applications, shows the sequence on both platforms. The sections following the flowchart provide more specific details for the individual platforms.
Start 1
Verify mbuild
No
Does the command mcc -m hello generate the hello application ? Yes
No
Stop
4-5
Stand-Alone 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 Set your compiler and linker settings Change compilers or compiler settings Switch between C and C++ development Build your application The MATLAB Compiler (mcc) automatically invokes mbuild under certain conditions. In particular, mcc -m or mcc -p invokes mbuild to perform compilation and linking. See the mcc reference page for complete details on which Compiler options you should use in order to use the mbuild script. If you do not want mcc to invoke mbuild automatically, you can use the -c option, for example, mcc -mc filename.
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-6
C C++
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-7
Stand-Alone Applications
Preparing to Compile
Note Refer to Supported ANSI C and C++ UNIX Compilers on page 2-4 for information about supported compilers and important limitations.
This simple method works for the majority of users. Assuming filename.c contains a main function, this example uses the systems 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-11. 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-8
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 Using the 'mbuild -setup' command selects an options file that is placed in ~/.matlab/R13 and used by default for 'mbuild'. An options file in the current working directory or specified on the command line overrides the default options file in ~/.matlab/R13. 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). The options files available for mbuild are: 1: /matlab/bin/mbuildopts.sh : Build and link with MATLAB C/C++ Math 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/R13 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.
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
4-9
Stand-Alone Applications
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/R13/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 specified options file for the current execution of mbuild only; it does not reset the default compiler.
4-10
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.
<matlab> is the MATLAB root directory <arch> is your architecture (i.e., alpha, hp700, hpux, lnx86, sgi, sgi64, or sol2)
It is convenient to place this command in a startup script such as ~/.cshrc. Then the system will be able to locate these shared libraries automatically, and you will not have to reissue the command at the start of each login session.
Note On all UNIX platforms, the Compiler library is shipped as a shared object (.so) file or shared library (.sl). Any Compiler-generated, stand-alone application must be able to locate the C/C++ libraries along the library path environment variable (SHLIB_PATH, LIBPATH, or LD_LIBRARY_PATH) in order to
4-11
Stand-Alone Applications
be found and loaded. Consequently, to share a Compiler-generated, stand-alone application with another user, you must provide all of the required shared libraries. For more information about the required shared libraries for UNIX, see Packaging UNIX Applications on page 4-13.
ans = 1.0000 + 7.0000i 2.0000 + 8.0000i 3.0000 + 9.0000i 4.0000 +10.0000i 5.0000 +11.0000i 6.0000 +12.0000i
This command should complete without errors. To run the stand-alone application, hello, invoke it as you would any other UNIX application, 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.
4-12
Distribution Caveats
Locating Shared Libraries. Remember to locate the shared libraries along the LD_LIBRARY_PATH (SHLIB_PATH on HP) environment variable so that they can
4-13
Stand-Alone Applications
Note If you distribute an application created with the math libraries on Digital UNIX, your users must have both the C++ and Fortran run-time shared libraries installed on their systems.
4-14
C C++
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-15
Stand-Alone Applications
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.
factory default options file for that compiler. If multiple compilers are found, you are prompted to select one.
Preparing to Compile
Compiler Restrictions
Some of the supported PC compilers have restrictions regarding their use with the MATLAB Compiler. Refer to Supported ANSI C and C++ PC Compilers on page 2-14 for important limitation information on the supported compilers. Other restrictions include Watcom 10.6 and 11.0 are not supported for building stand-alone applications. The Lcc C compiler does not support C++. The only compilers that support the building of COM objects are Borland C++Builder (versions 3.0, 4.0, 5.0, and 6.0) and Microsoft Visual C/C++ (versions 5.0, 6.0, and 7.0).
4-16
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
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 98 systems, if you get the error, out of environment space, see Out of Environment Space Running mex or mbuild on page 4-33 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
4-17
Stand-Alone Applications
[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.
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 Please choose your compiler for building stand-alone MATLAB applications. Would you like mbuild to locate installed compilers [y]/n? n Select a compiler: [1] Borland C++Builder version 6.0 [2] Borland C++Builder version 5.0 [3] Borland C++Builder version 4.0 [4] Borland C++Builder version 3.0 [5] Borland C/C++ version 5.02 [6] Borland C/C++ version 5.0 [7] Borland C/C++ (free command line tools) version 5.5 [8] Lcc C version 2.4 [9] Microsoft Visual C/C++ version 7.0 [10] Microsoft Visual C/C++ version 6.0 [11] Microsoft Visual C/C++ version 5.0 [0] None
4-18
Compiler: 10 Your machine has a Microsoft Visual C/C++ compiler located at D:\Applications\Microsoft Visual Studio. Do you want to use this compiler [y]/n? y Please verify your choices: Compiler: Microsoft Visual C/C++ 6.0 Location: D:\Applications\Microsoft Visual Studio Are these correct?([y]/n): y The default options file: "C:\WINNT\Profiles\username\ Application Data\MathWorks\MATLAB\R13\compopts.bat" is being updated... Installing the MATLAB Visual Studio add-in ... 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 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
4-19
Stand-Alone Applications
specific needs and save the modified file. This sets your default compilers 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 option 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 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.
Table 4-3: Compiler Options Files on the PC Compiler Master Options File bcc53compp.bat bcc54compp.bat bcc55compp.bat bcc56compp.bat lccopts.bat msvc50compp.bat
Borland C++Builder, Version 3.0 Borland C++Builder, Version 4.0 Borland C++Builder, Version 5.0 Borland C++Builder, Version 6.0 Lcc C, Version 2.4 Microsoft Visual C/C++, Version 5.0
4-20
Table 4-3: Compiler Options Files on the PC (Continued) Compiler Master Options File msvc60compp.bat msvc70compp.bat
Microsoft Visual C/C++, Version 6.0 Microsoft Visual C/C++, Version 7.0
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
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.
Temporarily Changing the Compiler. To temporarily change your C or C++ compiler,
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.
4-21
Stand-Alone Applications
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
This creates the file called ex1.exe. Stand-alone applications created on Windows 98/2000/Me or Windows NT always have the extension exe. The created application is a 32-bit MS-DOS console application.
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 stand-alone applications are WIN32 Dynamic Link Libraries. Before running a stand-alone application, you must ensure that the directory containing the DLLs is on your path. The directory must be on your operating system $PATH environment variable. On Windows NT, use the Control Panel to set the value.
ans =
4-22
This command should complete without errors. To run the stand-alone application, hello, invoke it as you would any other Windows console application, by typing its name on the MS-DOS command line. 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.
4-23
Stand-Alone Applications
Note The MATLAB add-in for Visual Studio does not currently work with Microsoft Visual C/C++, Version 7.0.
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
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.
2 To build stand-alone applications with the MATLAB add-in for Visual
Studio (requires the MATLAB Compiler and the MATLAB C/C++ Math Libraries), run the following command at the MATLAB command prompt:
mbuild -setup
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.)
3 For either mex or stand-alone support, you should also run the following
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
4-24
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. b Click on the Add-ins and Macro Files tab. c
Select 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. Selecting MATLAB for Visual Studio directs MSVC to automatically load the add-in when you start MSVC again.
4-25
Stand-Alone Applications
See the MATLABAddin.hlp file in the <matlab>\bin\win32 directory, or Click on the Help icon in the MATLAB add-in for Visual Studio toolbar
Help Icon
4-26
4-27
Stand-Alone Applications
Note If customers already have the MATLAB math and graphics run-time libraries installed on their system, they do not need to reinstall them. They only need to ensure that the library search path is configured correctly.
On UNIX Systems
On UNIX systems, your customers run the MATLAB Compiler Run-Time Library Installer by executing the mglinstaller command at the system prompt. Your customers can specify the name of the directory into which they want to install the libraries. By default, the installer puts the files in the current directory. After the installer unpacks and uncompresses the libraries, your customers must add the name of the bin/<ARCH> subdirectory to the LD_LIBRARY_PATH environment variable. (The equivalent variable on HP-UX systems is the SHLIB_PATH and LIBPATH on IBM AIX systems.) For example, if customers working on a Linux system specify the installation directory mgl_runtime_dir, then they must add mgl_runtime_dir/bin/glnx86 to the LD_LIBRARY_PATH environment variable.
On PCs
On PCs, your customers run the MATLAB Compiler Run-Time Library Installer by double-clicking on the mglinstaller.exe file. Your customers can specify the name of the directory into which they want to install the libraries. By default, the installer puts the files in the current directory. After the installer unpacks and uncompresses the libraries, your customers must add the bin\win32 subdirectory to the system path variable (PATH). For example, if your customers specify the installation directory mgl_runtime_dir, then they must add mgl_runtime_dir\bin\win32 to PATH.
4-28
The ordinal #### could not be located in the dynamic-link library dforrt.dll.
To fix this problem, locate dforrt.dll or dformd.dll in your Windows system directory and replace them with the corresponding files in the <MATLAB>\bin\win32 directory, where <MATLAB> represents the name of your MATLAB installation directory. This same solution works for customers of your application who encounter the same problem. Your customers can replace these files in the Windows system directory with the corresponding versions in the <MGLRUNTIMELIBRARY>\bin\win32 directory, where <MGLRUNTIMELIBRARY> is the name of the directory in which they installed the MATLAB Compiler Run-Time Libraries.
4-29
Stand-Alone Applications
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
creates a shared library named file1.ext, where ext is the platform-dependent shared library extension. For example, on the PC, it would be called file1.dll. The shared library exports the symbols times2 and times3.
4-30
You can use mbuild to create Component Object Model (COM) objects from MATLAB M-files. The collection of M-files is translated into a single COM class. MATLAB COM Builder supports multiple classes per component. The interface to the COM class is the same set of functions that are exported from a C shared library, but the Compiler supports both C and C++ code generation in producing COM objects.
mbuild automatically:
Invokes the Microsoft Interface Definition Language (MIDL) compiler Invokes the resource compiler Specifies the .DEF files Using mbuild options you can enable auto registration of the COM-compatible DLL.
Note Creating COM objects from MATLAB M-files is available on Windows only. The only compilers that support the building of COM objects with the MATLAB Compiler are Borland C++Builder (versions 3.0, 4.0, and 5.0) and Microsoft Visual C/C++ (versions 5.0, 6.0, and 7.0).
4-31
Stand-Alone Applications
You can use mbuild to create a COM object from MATLAB M-files that can be used as an Excel plug-in. The collection of M-files is translated into a single Excel plug-in. MATLAB Excel Builder supports one class per component. The interface to the COM class is the same set of functions that are exported from a C shared library, but the Compiler supports both C and C++ code generation in producing COM objects.
mbuild automatically:
Invokes the Microsoft Interface Definition Language (MIDL) compiler Invokes the resource compiler Specifies the .DEF files Using mbuild options you can enable auto registration of the COM-compatible DLL.
Note Creating Excel plug-ins from MATLAB M-files is available on Windows only. The only compilers that support the building of Excel plug-ins with the MATLAB Compiler are Borland C++Builder (versions 3.0, 4.0, and 5.0) and Microsoft Visual C/C++ (versions 5.0, 6.0, and 7.0).
4-32
Troubleshooting
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. Out of Environment Space Running mex or mbuild. On 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
On Windows Me systems, if you encounter this problem and are using the MATLAB add-in for Visual Studio, follow the procedure in Configuring on Windows 98 and Windows Me Systems on page 4-25.
Directory or File Not Writeable. If a destination directory or file is not writeable, ensure that the permissions are properly set. In certain cases, make sure that the file is not in use. 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 Not a Recognized Command. If mbuild is not recognized, verify that <MATLAB>\bin is on your path. On UNIX, it may be necessary to rehash.
4-33
Stand-Alone Applications
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 launches a new C shell to perform compilations, it executes the .cshrc script. If this script causes unexpected changes to the PATH environment variable, an error may occur. You can test this 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 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:
BORLAND for Borland C/C++, Version 5.3 MSVCDIR for Microsoft Visual C/C++, Version 5.0, 6.0, or 7.0 Next, mbuild searches the Windows registry for compiler entries.
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 reenable your antivirus software.
Verification of mbuild Fails. If none of the previous solutions addresses your difficulty with mbuild, contact Technical Support at The MathWorks at support@mathworks.com.
4-34
Troubleshooting
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.
If you have a licensing problem, contact The MathWorks. A list of contacts at The MathWorks is provided at the beginning of this manual.
MATLAB Compiler Does Not Generate Application. If you experience other problems with the MATLAB Compiler, contact Technical Support at The MathWorks at support@mathworks.com. Missing Functions In Callbacks. If your application includes a call to a function in a callback string or in a string passed as an argument to the feval function or an ODE solver, and this is the only place in your M-file this function is called, the Compiler will not compile the function. The Compiler does not look in these text strings for the names of functions to compile. See Fixing Callback Problems: Missing Functions on page 1-20 for more information.
4-35
Stand-Alone Applications
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-40 and Interfacing M-Code to C/C++ Code on page 5-46.
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-36
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
Figure 4-2, Building Two M-Files into a Stand-Alone C Application, illustrates the process of building a stand-alone C application from two M-files. The commands to compile and link depend on the operating system being used. See Building Stand-Alone C/C++ Applications on page 4-4 for details.
4-37
Stand-Alone Applications
main.m
mrank.m
mcc -t mrank.m
mbuild does
main_main.c
main.c
mrank.c
this part.
C Compiler
C Compiler
Object File
Object File
MATLAB M-File Math Library MATLAB Math Built-In Library ANSI C Library
MATLAB API Library MATLAB Utility Library MATLAB C/C++ Graphics Library Shaded blocks are user-written code.
Linker
Shadowed blocks are tools. Unshaded blocks are MATLAB Compiler-generated code.
Stand-Alone C Application
4-38
For C++ code, add -L cpp to the previous commands and use a C++ compiler instead of a C compiler.
4-39
Stand-Alone Applications
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
Compiling rank.m generates file rank.c, which contains a function named mlfRank. Then, compile the other M-files composing the stand-alone application.
mcc -t main.m mcc -t mrank.m mcc -W main main mrank rank.m
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
4-40
The resulting stand-alone application uses your customized version of mlfRank rather than the default version of mlfRank stored in the MATLAB M-File Math Library.
Note On PCs running Windows, as well as SGI, SGI64, and IBM, if a function in the MATLAB M-File Math Library calls mlfRank, it will call the one found in the Library and not your customized version. We recommend that you call your version of rank something else, for example, myrank.m.
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-41
Stand-Alone Applications
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 on page 5-21.
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-42
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-4. The MATLAB Compiler provides two different versions of mrankp.c in the <matlab>/extern/examples/compiler directory: mrankp.c contains a POSIX-compliant main function. mrankp.c sends its output to the standard output stream and gathers its input from the standard input stream. mrankwin.c contains a Windows version of mrankp.c.
4-43
Stand-Alone Applications
mrank.m
mbuild does
mrankp.c
this part.
C Compiler
C Compiler
Object File
Object File
MATLAB M-File Math Library MATLAB Math Built-In Library ANSI C Library
MATLAB API Library MATLAB Utility Library MATLAB C/C++ Graphics Library Shaded blocks are user-written code.
Linker
Shadowed blocks are tools. Unshaded blocks are MATLAB Compiler-generated code.
Stand-Alone C Application
4-44
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" /* Prototype for mlfMrank */ extern mxArray *mlfMrank( mxArray * ); main( int argc, char **argv ) { mxArray *N; /* Matrix containing n. */ mxArray *R; /* Result matrix. */ int n; /* Integer parameter from command line. */ /* Get any command line parameter. */ if (argc >= 2) { n = atoi(argv[1]); } else { n = 12; } PkgInitialize(); /* Initialize the library of M-Functions */ /* Create a 1-by-1 matrix containing n. */ N = mlfScalar(n); /* Call mlfMrank, the compiled version of mrank.m. */ R = mlfMrank(N);
4-45
Stand-Alone Applications
/* Print the results. */ mlfPrintMatrix(R); /* Free the matrices allocated during this computation. */ mxDestroyArray(N); mxDestroyArray(R); PkgTerminate(); } /* Terminate the library of M-functions */
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 in the MATLAB online documentation 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); mlfMrank returns a pointer to an mxArray * variable named R. The easiest way to display the contents of R is to call the mlfPrintMatrix convenience function: mlfPrintMatrix(R);
4-46
mlfPrintMatrix is one of the many routines in the MATLAB Math Built-In Library, which is part of the MATLAB Math Library.
Finally, mrankp must free the heap memory allocated to hold matrices and call the Compiler-generated termination function:
mxDestroyArray(N); mxDestroyArray(R); PkgTerminate();/* Terminate the library of M-functions */
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, which contains a function named multarg multargp.c, which contains a C function named main
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 #include #include #include #include <stdio.h> <string.h> <math.h> "matlab.h" "multpkg.h"/* Include Compiler-generated header file */
static void PrintHandler( const char *text ) { printf(text); } int main( ) { #define ROWS #define COLS /* Programmer written coded to call mlfMultarg */ 3 3
4-47
Stand-Alone Applications
mxArray *a, *b, *x, *y; double x_pr[ROWS * COLS] = {1, 2, 3, 4, double x_pi[ROWS * COLS] = {9, 2, 3, 4, double y_pr[ROWS * COLS] = {1, 2, 3, 4, double y_pi[ROWS * COLS] = {2, 9, 3, 4, double *a_pr, *a_pi, value_of_scalar_b;
5, 5, 5, 5,
6, 6, 6, 6,
7, 7, 7, 7,
8, 8, 8, 1,
multpkgInitialize();/* Call multpkg initialization */ /* Install a print handler to tell mlfPrintMatrix how to * display its output. */ mlfSetPrintHandler(PrintHandler); /* Create input matrix "x" */ x = mxCreateDoubleMatrix(ROWS, COLS, mxCOMPLEX); memcpy(mxGetPr(x), x_pr, ROWS * COLS * sizeof(double)); memcpy(mxGetPi(x), x_pi, ROWS * COLS * sizeof(double)); /* Create input matrix "y" */ y = mxCreateDoubleMatrix(ROWS, COLS, mxCOMPLEX); memcpy(mxGetPr(y), y_pr, ROWS * COLS * sizeof(double)); memcpy(mxGetPi(y), y_pi, ROWS * COLS * sizeof(double)); /* Call the mlfMultarg function. */ a = (mxArray *)mlfMultarg(&b, x, y); /* Display the entire contents of output matrix "a". */ mlfPrintMatrix(a); /* Display the entire contents of output scalar "b" */ mlfPrintMatrix(b); /* Deallocate temporary matrices. */ mxDestroyArray(a); mxDestroyArray(b); multpkgTerminate();/* Call multpkg termination */ return(0); }
4-48
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 12.5664 +34.5575i 18.8496 +18.8496i 143.4164 25.1327 +25.1327i 31.4159 +31.4159i 37.6991 +37.6991i 43.9823 +43.9823i 50.2655 +28.2743i 56.5487 +28.2743i
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-49
Stand-Alone Applications
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-50
5
Controlling Code Generation
This chapter describes the code generated by the MATLAB Compiler and the options that you can use to control code generation. Code Generation Overview (p. 5-2) Compiling Private and Method Functions (p. 5-5) The Generated Header Files (p. 5-8) Internal Interface Functions (p. 5-11) Supported Executable Types (p. 5-21) Formatting Compiler-Generated Code (p. 5-35) Including M-File Information in Compiler Output (p. 5-40) Interfacing M-Code to C/C++ Code (p. 5-46) Sample source files and generated filenames Working with private and method functions Generated C and C++ header files Generated C and C++ interface functions Generated wrapper functions Controlling the look of generated C/C++ code Controlling annotation in generated C/C++ code Calling C/C++ functions from M-code
theImage = zeros(1000,1000); corners = [866 1;1 500;866 1000]; startPoint = [866 1]; theRand = rand(numPoints,1); theRand = ceil(theRand*3); for i=1:numPoints startPoint = floor((corners(theRand(i),:)+startPoint)/2); theImage(startPoint(1),startPoint(2)) = 1; end
foo M-File
function [a, b] = foo(x, y) if nargout == 0 elseif nargout == 1 a = x; elseif nargout == 2 a = x;
5-2
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: C or C++ code, depending on your target language (-L) specification Header file Wrapper file, depending on the -W option 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. Table 5-1, Compiler-Generated Files, shows the names of the files generated when you compile a generic M-file Table 5-1(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 and the COM target.
5-3
Table 5-1: Compiler-Generated Files C Header Code Main Wrapper (-W main) MEX Wrapper (-W mex) file.h file.c file_main.c file_mex.c C++ file.hpp file.cpp file_main.cpp
N/A (C++ MEX-files are not supported.) N/A (C++ MEX-files are not supported.)
filelist.cpp filelist.hpp filelist.mlib
file_simulink.c
filelist.c filelist.h filelist.exports filelist.mlib compname_idl.idl compname_com.hpp compname_com.cpp compname_dll.cpp compname.def compname.rc
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 books printed page. For more information about the page-width option, see Formatting Compiler-Generated Code on page 5-35.
5-4
Note Although MATLAB Compiler 3.0 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 documented in this table.
Name foo.m xxx/private/foo.m Description
5-5
Description foo.m method to operate on cell arrays foo.m private to methods that operate on
cell arrays This table lists the functions you can specify on the command line and their corresponding function and filenames.
Function
foo
C Function
mlfFoo mlxFoo mlNFoo mlfNFoo mlfVFoo mlf_cell_foo mlx_cell_foo mlN_cell_foo mlfN_cell_foo mlfV_cell_foo mlfXXX_private_foo mlxXXX_private_foo mlNXXX_private_foo mlfNXXX_private_foo mlfVXXX_private_foo mlfcell_private_foo mlxcell_private_Foo mlNcell_private_Foo mlfNcell_private_Foo mlfVcell_private_Foo
C++ Function
foo Nfoo Vfoo mlxFoo
Filename
foo.c foo.h foo.cpp foo.hpp
@cell/foo
xxx/private/foo
@cell/private/foo
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
5-6
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
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
5-8
extern mxArray * mlfGasket(mxArray * numPoints); extern void mlxGasket(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[]); #ifdef __cplusplus } #endif #endif
5-9
extern mwArray gasket(mwArray numPoints = mwArray::DIN); #ifdef __cplusplus extern "C" #endif void mlxGasket(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[]); #endif
5-10
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.
Note Comments have been added to the generated code to highlight where the input and output arguments are processed and where functions are called.
/* * * * * * * *
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.
5-11
*/ void mlxGasket(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[]) { mxArray * mprhs[1]; mxArray * mplhs[1]; int i; /* ------------- Input Argument Processing ------------ */ if (nlhs > 1) { mlfError( mxCreateString( "Run-time Error: File: gasket Line: 1 Column: " "1 The function \"gasket\" was called with mor" "e than the declared number of outputs (1)."), NULL); } if (nrhs > 1) { mlfError( mxCreateString( "Run-time Error: File: gasket Line: 1 Column: " "1 The function \"gasket\" was called with mor" "e than the declared number of inputs (1)."), NULL); } for (i = 0; i < 1; ++i) { mplhs[i] = NULL; } for (i = 0; i < 1 && i < nrhs; ++i) { mprhs[i] = prhs[i]; } for (; i < 1; ++i) { mprhs[i] = NULL; } /* ---------------------------------------------------- */ mlfEnterNewContext(0, 1, mprhs[0]); /* -------- Call to C Implementation Function --------- */ mplhs[0] = Mgasket(nlhs, mprhs[0]);
5-12
5-13
This is the corresponding mlfNF interface function (mlfNFoo) for the foo.m example described earlier in this chapter. This function calls the Mfoo function that appears in foo.c:
/* * The function "mlfNFoo" 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 * interface, which dynamically calculates the number of * outputs based on the number of non-NULL inputs it * receives. This function processes any input arguments * and passes them to the implementation version of the * function, appearing above. */ mxArray * mlfNFoo(int nargout, mxArray * * b, mxArray * x, mxArray * y) { /* ------------- Input Argument Processing ------------ */ mxArray * a = NULL; mxArray * b__ = NULL; mlfEnterNewContext(1, 2, b, x, y); /* ----------------- Call M-Function ------------------ */ a = Mfoo(&b__, nargout, x, y); /* ------------- Output Argument Processing ----------- */ mlfRestorePreviousContext(1, 2, b, x, y); if (b != NULL) { mclCopyOutputArg(b, b__); } else { mxDestroyArray(b__); } return mlfReturnValue(a); }
5-14
5-15
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++.
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(); { // ------------- Input Argument Processing --------------mwArray mprhs[1]; mwArray mplhs[1];
5-16
int i; mclCppUndefineArrays(1, mplhs); if (nlhs > 1) { error( mwVarargin( mwArray( "Run-time Error: File: gasket Line:" " 1 Column: 1 The function \"gasket" "\" was called with more than the d" "eclared number of outputs (1)."))); } if (nrhs > 1) { error( mwVarargin( mwArray( "Run-time Error: File: gasket Line:" " 1 Column: 1 The function \"gasket" "\" was called with more than the d" "eclared number of inputs (1)."))); } 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 Processing -------------plhs[0] = mplhs[0].FreezeData(); } MW_END_MLX(); }
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:
5-17
// // 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 = mwArray::UNDEFINED; // ----------------- Call M-Function --------------------theImage = Mgasket(nargout, numPoints); // ------------- Output Argument Processing -------------return theImage; }
NF 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 interface, which dynamically calculates the number of outputs based on the number of non-NULL inputs it receives. This function processes any input arguments and passes them to the implementation version of the
5-18
// function, appearing above. // mwArray Nfoo(int nargout, mwArray * b, mwArray x, mwArray y) { // ------------- Input Argument Processing --------------mwArray a = mwArray::UNDEFINED; mwArray b__ = mwArray::UNDEFINED; // ----------------- Call M-Function --------------------a = Mfoo(&b__, nargout, x, y); // ------------- Input Argument Processing --------------if (b != NULL) { *b = b__; } // ------------- Output Argument Processing -------------return a; }
5-19
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 // version still returns an output (which, in MATLAB, would // be assigned to the "ans" variable), it deallocates the // output. This function processes any input arguments and // passes them to the implementation version of the // function, appearing above. // void Vfoo(mwArray x, mwArray y) { // ------------- Input Argument Processing --------------mwArray a = mwArray::UNDEFINED; mwArray b = mwArray::UNDEFINED; // ----------------- Call M-Function --------------------a = Mfoo(&b, 0, x, y); }
5-20
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-21
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 the MATLAB documentation. 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-22
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:\>
The difference between the MATLAB and DOS/UNIX environments is the handling of the return value. In MATLAB, the return value is handled by printing its value; in the DOS/UNIX shell, the return value is handled as the return status code. When you compile a function into a POSIX main application, the first return value from the function is coerced to a scalar and is returned to the POSIX shell.
5-23
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 The sizes structure The S-functions sample times array The S-functions states and work vectors The global variables and constant pool For more information about Simulink S-function requirements, see Writing S-Functions in the Simulink documentation.
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-26.
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-24
This example uses several functions from the toolbox\matlab\timefun directory (weekday, date, tic, calendar, toc) to create a library wrapper. The -W lib:libtimefun -L C options produce the files shown in this table.
File libtimefun.c libtimefun.h libtimefun.exports libtimefun.mlib 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 -B csharedlib:libtimefun weekday data tic calendar toc
The bundle file option, -B <filename>:[<a1>,<a2>,...,<an>], replaces the entire expression on the mcc command line with the contents of the specified file and it allows you to use replacement parameters. This example uses the csharedlib bundle file and replaces the expression
5-25
-B csharedlib:libtimefun
with
-t -W lib:libtimefun -T link:lib -h libmmfile.mlib
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.
Note You can use the -B option with a replacement expression as is at the DOS or UNIX prompt. To use -B with a replacement expression at the MATLAB prompt, you must enclose the expression that follows the -B in single quotes when there is more than one parameter passed. For example,
>>mcc -B csharedlib:libtimefun weekday data tic calendar toc
can be used as is at the MATLAB prompt because libtimefun is the only parameter being passed. If the example had two or more parameters, then the quotes would be necessary as in
>>mcc -B 'cexcel:component,class,1.0' weekday data tic calendar toc
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
5-26
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 functions, 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 filess corresponding shared library. When the executable is created, it is linked against the shared library. For example, on the PC, the executable timer.exe is created and it is linked against libtimefun.dll. 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.
5-27
Note On the mcc command line, you can access any mlib file by including the full path to the file. For example:
mcc -m timer /pathname/libtimefun.mlib
Restrictions.
(UNIX) The first three characters of the filename must be lib. (PC and UNIX) You cannot rename the file. (PC and UNIX) Both the shared library and the mlib file must be in the same directory at compile time. (PC and UNIX) At run time, the path to the shared library must be on the systems search path. For more information about setting the path on the PC, see Shared Libraries on page 4-22. For UNIX information, see Locating Shared Libraries on page 4-11. You do not need the mlib file present when running the executable that links to the shared library.
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-28
This example uses several functions from the toolbox\matlab\timefun directory (weekday, date, tic, calendar, toc) to create a C++ library called libtimefun. The -W lib:libtimefun -L Cpp options produce the C++ library files shown in this table.
File libtimefun.cpp libtimefun.hpp 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
COM Components
The COM wrapper file allows you to create COM components from MATLAB M-files. The Compiler options that generate the COM wrappers are
-W -W -W -W com:<component_name>[,<class_name>[,<major>.<minor>]] comhg:<component_name>[,<class_name>[,<major>.<minor>]] excel:<component_name>[,<class_name>[,<major>.<minor>]] excelhg:<component_name>[,<class_name>[,<major>.<minor>]]
5-29
The COM wrapper options create a superset of the files created when producing a C or C++ library wrapper. In addition to the C or C++ library files, the COM wrapper creates the files shown in the following table.
File <component_name>_idl.idl <component_name>_com.hpp <component_name>_com.cpp <component_name>_dll.cpp <component_name>.def <component_name>.rc Description
Interface description file for COM C++ header file for the COM class C++ source file for the COM class DLL interface for the COM object Definition file for the COM DLL Resource file for the COM DLL
If the <class_name> is not specified, it defaults to <component_name>. If the version number is not specified, it defaults to the latest version built or 1.0, if there is no previous version. The COM wrapper option creates all the required code and files to create a single COM object that contains all of the compiler-generated interfaces. It creates a single COM class with the same name as the specified <class_name> and a corresponding interface class called I<class_name>. It uses the major and minor version numbers to control the major and minor version numbers of the COM interface that is produced. The Compiler can generate either C or C++ code for the compiler M-files, but the created COM interface will always require C++. This is a requirement of COM and not particular to the MATLAB Compiler. All of the extra files generated by the MATLAB Compiler that are required for producing the COM objects are added to the mbuild command line. The details of how mbuild processes the new file types (.def, .rc, and .idl) are specified in How mbuild Processes the File Types on page 5-32. If the major and minor version numbers are specified, the Compiler replaces any existing type library with the specified new version number. If no version numbers are specified and there is an existing type library, the Compiler replaces the current version.
5-30
When calling mbuild to link a library, the .dll file will be <component_name>_<major>_<minor>.dll. This will prevent new versions from conflicting with each other. The user never uses the DLL name. It is not necessary to specify this name to the system because COM locates component DLLs using the Windows registry. The MATLAB Compiler uses the -b option to generate a Visual Basic (.bas) file that contains the Microsoft Excel Formula Function interface to the compiler-generated COM object. When imported into the workbook, this Visual Basic code allows the MATLAB function to be seen as a cell formula function. The -i option causes the Compiler to include only the M-files that are specified on the command line as exported interfaces. If additional M-files are compiled as a result of being located by the -h option, they are not included in the exported interface that is produced by the MATLAB Compiler. The bundle option (-B) provides a means to replace its expression on the mcc command line with the contents of the specified file. Also, it lets you include replacement parameters so that any Compiler options that accept names and version numbers will be expanded properly. For more information on the bundle option including the available bundle files, see -B <filename>:[<a1>,<a2>,...,<an>] (Bundle of Compiler Settings) on page 7-41.
Note You can use the -B option with a replacement expression as is at the DOS or UNIX prompt. To use -B with a replacement expression at the MATLAB prompt, you must enclose the expression that follows the -B in single quotes when there is more than one parameter passed. For example,
>>mcc -B csharedlib:libtimefun weekday data tic calendar toc
can be used as is at the MATLAB prompt because libtimefun is the only parameter being passed. If the example had two or more parameters, then the quotes would be necessary as in
>>mcc -B 'cexcel:component,class,1.0' weekday data tic calendar toc
5-31
COM Signature
When using the MATLAB Compiler and its COM wrapper option with an M-file, the Compiler produces and registers a COM-compatible DLL. The Compiler produces the necessary function calls in accordance with these signatures.
M-Function Signature. [Y1, Y2, , Varargout] = f(X1, X2, , Varargin)
5-32
C Signature. void mlxF(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]); mxArray *mlfNF( int mxArray mxArray . . mxArray mxArray . . ... ); COM/IDL Signature. HRESULT f([in] long nargout, [in,out] VARIANT* Y1, [in,out] VARIANT* Y2, . . [in,out] VARIANT* varargout, [in] VARIANT X1, [in] VARIANT X2, . . [in] VARIANT varargin); nargout, ** y1, **y2,
*x1, *x2,
The COM run-time performs all of the conversion between the COM types and MATLAB arrays. For details on this conversion, see the MATLAB Excel Builder or MATLAB COM Builder documentation.
5-33
Note Stand-alone applications require that the MATLAB C/C++ Math Library be purchased for each platform where the Compiler-generated code will be executed.
5-34
The remaining sections focus on the different choices you can use.
Note To improve the readability of your generated code, turn off optimizations with -O none or -g. The examples in this section have optimizations off.
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.
5-35
Default Width
Not specifying a page width formatting option uses the default of 80. Using
mcc -xg gasket
Page Width = 40
This example specifies a page width of 40:
mcc -xg -F page-width:40 gasket
5-36
NULL)); /* * * corners = [866 1;1 500;866 1000]; */ mclMline(15); mlfAssign( &corners, mlfDoubleMatrix( 3, 2, _array0_, (double *)NULL)); /* * startPoint = [866 1]; */ mclMline(16); mlfAssign( &startPoint, mlfDoubleMatrix( 1, 2, _array1_, (double *)NULL)); /* * theRand = rand(numPoints,1); */ mclMline(17); mlfAssign( &theRand, mlfNRand( 1, mclVa(numPoints, "numPoints"), mlfScalar(1), NULL)); . . .
5-37
Default Indentation
Not specifying indent formatting options uses the default of four spaces for statements and two spaces for expressions. For example, using
mcc -xg gasket
5-38
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 -xg gasket
5-39
You can combine annotation options, for example, selecting both comments and #line directives. The remaining sections focus on the different choices you can use.
Note To improve the readability of your generated code, turn off optimizations with -O none or -g. The examples in this section have optimizations off.
5-40
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 (This is the hello ...) in the middle of the routine:
static void Mhello(void) { mclMlineEnterFunction("D:\\work\\hello.m", "hello") mexLocalFunctionTable save_local_function_table_ = mclSetCurrentLocalFunctionTable(&_local_function_table_hello); mxArray * ans = NULL; /* * This is the hello, world function written in M code */ mclMline(3); mclAssignAns( &ans, mlfNFprintf(0, mlfScalar(1), mxCreateString("Hello, World\\n"), NULL)); mxDestroyArray(ans); mclSetCurrentLocalFunctionTable(save_local_function_table_); mclMlineExitFunction(); }
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. This code snippet contains both comments and source code:
static void Mhello(void) { mclMlineEnterFunction("D:\\work\\hello.m", "hello") mexLocalFunctionTable save_local_function_table_ = mclSetCurrentLocalFunctionTable(&_local_function_table_hello); mxArray * ans = NULL; /* * % This is the hello, world function written in M code * fprintf(1,'Hello, World\n' ); */ mclMline(3); mclAssignAns( &ans, mlfNFprintf(0, mlfScalar(1), mxCreateString("Hello, World\\n"), NULL));
5-41
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) { mclMlineEnterFunction("D:\\work\\hello.m", "hello") mexLocalFunctionTable save_local_function_table_ = mclSetCurrentLocalFunctionTable(&_local_function_table_hello); mxArray * ans = NULL; mclMline(3); mclAssignAns( &ans, mlfNFprintf(0, mlfScalar(1), mxCreateString("Hello, World\\n"), NULL)); mxDestroyArray(ans); mclSetCurrentLocalFunctionTable(save_local_function_table_); mclMlineExitFunction(); }
was generated by another tool (MATLAB Compiler) and they identify the correspondence between the generated code and the original source code (M-file). You can use the #line directives to help debug your M-file(s). Most C language debuggers can display your M-file source code. These debuggers allow you to set breakpoints, single step, and so on at the M-file code level when you use the #line directives. Use the line:setting option to include #line preprocessor directives in your generated C or C++ output. The possible values for setting are on off Not specifying any line setting uses the default of off, which does not include any #line preprocessor directives in the generated C/C++ source.
5-42
Note When using the #line directive, the page-width directive is disabled in order to make the code work properly with the C debugger.
The Hello, World example produces the following code segment when this option is selected. (Note that several lines have been truncated for readability.)
#line 1 "D:\\work\\hello.m" /* Line 1 */ static void Mhello(void) { #line 1 "D:\\work\\hello.m" /* Line 1 */ mclMlineEnterFunction("D:\\work\\hello.m", "hello") #line 1 "D:\\work\\hello.m" /* Line 1 */ mexLocalFunctionTable save_local_function_table_ = --> #line 1 "D:\\work\\hello.m" /* Line 1 */ mxArray * ans = NULL; /* * % This is the hello, world function written in M code * fprintf(1,'Hello, World\n' ); */ #line 3 "D:\\work\\hello.m" /* Line 3 */ mclMline(3); #line 3 "D:\\work\\hello.m" /* Line 3 */ mclAssignAns(&ans, mlfNFprintf(0, mlfScalar(1), mxCreateString("Hello,--> #line 3 "D:\\work\\hello.m" /* Line 3 */ mxDestroyArray(ans); #line 3 "D:\\work\\hello.m" /* Line 3 */ mclSetCurrentLocalFunctionTable(save_local_function_table_); #line 3 "D:\\work\\hello.m" /* Line 3 */ mclMlineExitFunction(); #line 3 "D:\\work\\hello.m" /* Line 3 */ }
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 3 points to lines in the C code that were produced by line 3 of the M-file, or
fprintf(1,'Hello, World\n' );
5-43
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-44
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. Since try catch end is not available in g++, do not use the -A debugline:on option on Linux when generating a C++ application.
5-45
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 y = zeros(1, 100); %Pre-allocate the matrix for i = 1:100 y(i) = collect_one; end function y = collect_one persistent t; if (isempty(t)) t = 0; end t = t + 0.05; y = sin(t);
The next step is to replace the implementation of the collect_one function with a C implementation that provides the correct value from the device each time it is requested. This is accomplished by using the %#external pragma. The %#external pragma informs the MATLAB 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. Any M-function may contain this pragma (local, global,
5-46
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 y = zeros(1, 100); % pre-allocate the matrix for i = 1:100 y(i) = collect_one; end 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-47
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> extern double measure_from_device(void); mxArray * Mcollect_collect_one(int nargout_); { return( mlfScalar( measure_from_device() )); } double measure_from_device(void) { static double t = 0.0; t = t + 0.05; return sin(t); }
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 -mc collect.m
By examining the Compiler-generated C code, you should easily be able to determine how to implement this interface. To compile collect.m to a MEX-file, use
mcc -x collect.m measure.c
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-48
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
This implies that myfunctionwritteninc is an M-function that will be called using feval. The Compiler will look up this function to determine the correct number of input and output variables.
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-49
5-50
6
Optimizing Performance
The MATLAB Compiler can perform various optimizations on your M-file source code that can make the performance of the generated C/C++ code much faster than the performance of the M-code in the MATLAB interpreter. MATLAB Compiler 3.0 provides a series of optimizations that can help speed up your compiled code. This chapter describes the optimization options. 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. Optimization Bundles (p. 6-2) Optimizing Arrays (p. 6-4) Optimizing Loops (p. 6-6) Optimizing Conditionals (p. 6-9) Optimizing MATLAB Arrays (p. 6-10) Bundles that allow you to select the most common optimization options Improving the performance of code that manipulates scalar arrays Improviing the performance of simple one- and two-dimensional array index expressions Reducing the MATLAB conditional operators to scalar C conditional operators Accelerates scalar math operations
Optimizing Performance
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>:[<a1>,<a2>,...,<an>] (Bundle of Compiler Settings) on page 7-41.
6-2
Optimization Bundles
6-3
Optimizing Performance
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 run-time, thus improving run-time 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;
In the optimized case, this code uses _mxarray0_, which is initialized at program start-up to hold the correct value. All constants with the same value use the same mxArray variable in the constant pool.
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-4
Optimizing Arrays
Scalars
(fold_mxarrays) This option is equivalent to using both fold_scalar_mxarrays and fold_non_scalar_mxarrays. It is included for compatibility with P-code generation.
6-5
Optimizing Performance
Optimizing Loops
Simple Indexing
(array_indexing) This optimization improves the performance of simple oneand 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);
The mclArrayRef2 function is optimized for two-dimensional indexing. mclArrayRef1 is used for one-dimensional indexing.
Loop Simplification
(optimize_integer_for_loops) This optimization detects when a loop starts and increments with integers. It 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-6
Optimizing Loops
Note This optimization causes the variable names in the resulting C program to differ from those in the M-file. Therefore, we recommend that you do not use this option when debugging.
For example:
function test(x) for i = 1:length(x)-1 x(i) = x(i) + x(i+1) end
6-7
Optimizing Performance
6-8
Optimizing Conditionals
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-9
Optimizing Performance
Scalar Doubles
(speculate) This optimization is similar to the technology used by MATLAB to accelerate scalar double math operations. It makes educated guesses about the type of MATLAB arrays, and optimizes the code accordingly. This optimization can have dramatic impact on scalar double MATLAB code and more modest impact on small array operations. This optimization is off by default.
6-10
7
Reference
Reference
Functions By Category
Pragmas
%#external %#function %#mex
Compiler Functions
mbchar mbcharscalar mbcharvector mbint mbintscalar mbintvector mbreal mbrealscalar mbrealvector mbscalar mbvector
Impute char matrix. Impute character scalar. Impute char vector. Impute integer. Impute integer scalar. Impute integer vector. Impute real. Impute real scalar. Impute real vector. Impute scalar. Impute vector.
Customize building and linking. Invoke MATLAB Compiler. Overview of Compiler options. Simplify basic compilation tasks.
7-2
Optimization Options Improve the performance of the generated C/C++ code. Compiler and Control Compiler behavior. Environment Options
mbuild/mex Options
7-3
Functions By Name
%#external . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-5 %#function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6 %#mex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7 mbchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8 mbcharscalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9 mbcharvector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10 mbint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-11 mbintscalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-13 mbintvector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-14 mbreal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-15 mbrealscalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-16 mbrealvector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-17 mbscalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-18 mbvector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-19 mbuild . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-20 mcc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-25
7-4
%#external
7%#external
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 on page 5-46.
7-5
%#function
7%#function
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
This implies that myfunctionwritteninc is an M-function that will be called using feval. The Compiler will look up this function to determine the correct number of input and output variables. Therefore, you need to provide a dummy M-function that contains a function line and a %#external pragma, such as
function y = myfunctionwritteninc( a, b, c ); %#external
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
7%#mex
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
mbchar
7mbchar
The statement
mbchar(x)
causes the MATLAB Compiler to impute that x is a char matrix. At run-time, if mbchar determines that x does not hold a char matrix, mbchar issues an error message and halts execution of the MEX-file.
mbchar tells the MATLAB interpreter to check whether x holds a char matrix. If x does not, mbchar issues an error message and halts execution of the M-file. The MATLAB interpreter does not use mbchar to impute x.
Note that mbchar only tests x at the point in an M-file or MEX-file where an mbchar call appears. In other words, an mbchar call tests the value of x only once. If x becomes something other than a char matrix after the mbchar test, mbchar cannot issue an error message. 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'.
See Also
7-8
mbcharscalar
7mbcharscalar
The statement
mbcharscalar(x)
causes the MATLAB Compiler to impute that x is a character scalar, i.e., an unsigned short variable. At run-time, if mbcharscalar determines that x holds a value other than a character scalar, mbcharscalar issues an error message and halts execution of the MEX-file.
mbcharscalar tells the MATLAB interpreter to check whether x holds a character scalar value. If x does not, mbcharscalar issues an error message and halts execution of the M-file. The MATLAB interpreter does not use mbcharscalar to impute 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.
Example
See Also
7-9
mbcharvector
7mbcharvector
The statement
mbcharvector(x)
causes the MATLAB Compiler to impute that x is a char vector. At run-time, if mbcharvector determines that x holds a value other than a char vector, mbcharvector issues an error message and halts execution of the MEX-file.
mbcharvector tells the MATLAB interpreter to check whether x holds a char vector value. If x does not, mbcharvector issues an error message and halts execution of the M-file. The MATLAB interpreter does not use mbcharvector to impute x.
Note that mbcharvector only tests x at the point in an M-file or MEX-file where an mbcharvector call appears. In other words, an mbcharvector call tests the value of x only once. If x becomes something other than a char vector after the mbcharvector test, mbcharvector cannot issue an error message.
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.
Example
This code in MATLAB causes mbcharvector to generate an error message because, although n is a vector, n contains one value that is not a char:
n = [1:5]; mbcharvector(n) ??? Error using ==> mbchar Argument to mbchar must be of class 'char'.
See Also
7-10
mbint
7mbint
The statement
mbint(x)
causes the MATLAB Compiler to impute that x is an integer. At run-time, if mbint determines that x holds a noninteger value, the generated code issues an error message and halts execution of the MEX-file.
mbint tells the MATLAB interpreter to check whether x holds an integer value. If x does not, mbint issues an error message and halts execution of the M-file. The MATLAB interpreter does not use mbint to impute a data type to x.
Note that mbint only tests x at the point in an M-file or MEX-file where an mbint call appears. In other words, an mbint call tests the value of x only once. If x becomes a noninteger after the mbint test, mbint cannot issue an error message.
mbint defines an integer as any scalar, vector, or matrix that contains only integer or string values. For example, mbint considers n to be an integer because all elements in n are integers. n = [5 7 9];
If n is a complex number, then mbint considers n to be an integer if both its real and imaginary parts are integers. For example, mbint considers the value of n an integer.
n = 4 + 7i mbint does not consider the value of x an integer because one of the parts (the imaginary) has a fractional component:
7-11
mbint
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.
See Also
7-12
mbintscalar
7mbintscalar
The statement
mbintscalar(x)
causes the MATLAB Compiler to impute that x is an integer scalar. At run-time, if mbintscalar determines that x holds a value other than an integer scalar, mbintscalar issues an error message and halts execution of the MEX-file.
mbintscalar tells the MATLAB interpreter to check whether x holds an integer scalar value. If x does not, mbintscalar issues an error message and halts execution of the M-file. The MATLAB interpreter does not use mbintscalar to impute x.
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.
Example
This code in MATLAB causes mbintscalar to generate an error message because, although n is a scalar, n does not hold an integer value:
n = 4.2; mbintscalar(n) ??? Error using ==> mbint Argument to mbint must be integer.
See Also
7-13
mbintvector
7mbintvector
The statement
mbintvector(x)
causes the MATLAB Compiler to impute that x is an integer vector. At run-time, if mbintvector determines that x holds a value other than an integer vector, mbintvector issues an error message and halts execution of the MEX-file.
mbintvector tells the MATLAB interpreter to check whether x holds an integer vector value. If x does not, mbintvector issues an error message and halts execution of the M-file. The MATLAB interpreter does not use mbintvector to impute x.
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.
Example
This code in MATLAB causes mbintvector to generate an error message because, although all the values of n are integers, n is a matrix rather than a vector:
n = magic(2) n = 1 3 4 2 mbintvector(n) ??? Error using ==> mbvector Argument to mbvector must be a vector.
See Also
7-14
mbreal
7mbreal
The statement
mbreal(x)
causes the MATLAB Compiler to impute that x is real (not complex). At run-time, if mbreal determines that x holds a complex value, mbreal issues an error message and halts execution of the MEX-file.
mbreal tells the MATLAB interpreter to check whether x holds a real value. If x does not, mbreal issues an error message and halts execution of the M-file. The MATLAB interpreter does not use mbreal to impute x.
Note that mbreal only tests x at the point in an M-file or MEX-file where an mbreal call appears. In other words, an mbreal call tests the value of x only once. If x becomes complex after the mbreal test, mbreal cannot issue an error message. A real value is any scalar, vector, or matrix that contains no imaginary components.
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.
See Also
7-15
mbrealscalar
7mbrealscalar
The statement
mbrealscalar(x)
causes the MATLAB Compiler to impute that x is a real scalar. At run-time, if mbrealscalar determines that x holds a value other than a real scalar, mbrealscalar issues an error message and halts execution of the MEX-file.
mbrealscalar tells the MATLAB interpreter to check whether x holds a real scalar value. If x does not, mbrealscalar issues an error message and halts execution of the M-file. The MATLAB interpreter does not use mbrealscalar to impute x.
Note that mbrealscalar only tests x at the point in an M-file or MEX-file where an mbrealscalar call appears. In other words, an mbrealscalar call tests the value of x only once. If x becomes a vector after the mbrealscalar test, mbrealscalar cannot issue an error message.
mbrealscalar defines a real scalar as any value that meets the criteria of both mbreal and mbscalar.
Example
This code in MATLAB causes mbrealscalar to generate an error message because, although n contains only real numbers, n is not a scalar:
n = [17.2 15.3]; mbrealscalar(n) ??? Error using ==> mbscalar Argument of mbscalar must be scalar.
See Also
7-16
mbrealvector
7mbrealvector
The statement
mbrealvector(x)
causes the MATLAB Compiler to impute that x is a real vector. At run-time, if mbrealvector determines that x holds a value other than a real vector, mbrealvector issues an error message and halts execution of the MEX-file.
mbrealvector tells the MATLAB interpreter to check whether x holds a real vector value. If x does not, mbrealvector issues an error message and halts execution of the M-file. The MATLAB interpreter does not use mbrealvector to impute x.
Note that mbrealvector only tests x at the point in an M-file or MEX-file where an mbrealvector call appears. In other words, an mbrealvector call tests the value of x only once. If x becomes complex after the mbrealvector test, mbrealvector cannot issue an error message.
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.
Example
This code in MATLAB causes mbrealvector to generate an error message because, although n is a vector, n contains one imaginary number:
n = [5 2+3i]; mbrealvector(n) ??? Error using ==> mbreal Argument to mbreal must be real.
See Also
7-17
mbscalar
7mbscalar
The statement
mbscalar(x)
causes the MATLAB Compiler to impute that x is a scalar. At run-time, if mbscalar determines that x holds a nonscalar value, mbscalar issues an error message and halts execution of the MEX-file. mbscalar tells the MATLAB interpreter to check whether x holds a scalar value. If x does not, mbscalar issues an error message and halts execution of the M-file. The MATLAB interpreter does not use mbscalar to impute x. Note that mbscalar only tests x at the point in an M-file or MEX-file where an mbscalar call appears. In other words, an mbscalar call tests the value of x only once. If x becomes nonscalar after the mbscalar test, mbscalar cannot issue an error message.
mbscalar defines a scalar as a matrix whose dimensions are 1-by-1.
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.
See Also
7-18
mbvector
7mbvector
The statement
mbvector(x)
causes the MATLAB Compiler to impute that x is a vector. At run-time, if mbvector determines that x holds a nonvector value, mbvector issues an error message and halts execution of the MEX-file.
mbvector causes the MATLAB interpreter to check whether x holds a vector value. If x does not, mbvector issues an error message and halts execution of the M-file. The MATLAB interpreter does not use mbvector to impute x.
Note that mbvector only tests x at the point in an M-file or MEX-file where an mbvector call appears. In other words, an mbvector call tests the value of x only once. If x becomes a nonvector after the mbvector test, mbvector cannot issue an error message.
mbvector defines a vector as any matrix whose dimensions are 1-by-n or n-by-1. All scalars are also vectors (though most vectors are not scalars).
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.
See Also
7-19
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
mbuild [option1 ... optionN] sourcefile1 [... sourcefileN] [objectfile1 ... objectfileN] [libraryfile1 ... libraryfileN] [exportfile1 ... exportfileN]
Syntax
Note Supported types of source files are: .c, .cpp, .idl, .rc. To specify IDL source files to be compiled with the MIDL Compiler, add <filename>.idl to the mbuild command line; to specify a DEF file, add <filename>.def to the command line; to specify an RC file, add <filename>.rc to the command line. Source files that are not one of the supported types are passed to the linker.
Description
mbuild is a script that supports various options that allow you to customize the building and linking of your code. Table 7-1, mbuild Options, lists the mbuild options. If no platform is listed, the option is available on both UNIX and Microsoft Windows. Table 7-1: mbuild Options Option -<arch> Description
(UNIX) Assume local host has architecture <arch>. Possible values for <arch> include sol2, hpux, hp700, alpha, ibm_rs, sgi, and glnx86. (Windows) Replace @<response_file> on the mbuild command line with the contents of the text file, response_file. Compile only. Do not link. Creates an object file but not an executable. Define a symbol name to the C/C++ preprocessor. Equivalent to a #define <name> directive in the source.
@<response_file>
-c
-D<name>
7-20
mbuild
Define a symbol name and value to the C/C++ preprocessor. Equivalent to a #define <name> <value> directive in the source. (UNIX) Define a symbol name and value to the C preprocessor. Equivalent to a #define <name> <value> directive in the source. Specify location and name of options file to use. Overrides the mbuild default options file search mechanism. Create a debuggable executable. If this option is specified, mbuild appends the value of options file variables ending in DEBUGFLAGS with their corresponding base variable. This option also disables the mbuild default behavior of optimizing built object code. Help; prints a description of mbuild and the list of options. Add <pathname> to the list of directories to search for #include files. Inline matrix accessor functions (mx*). The generated executable may not be compatible with future versions of the MATLAB C/C++ Math Library or MATLAB C/C++ Graphics Library. (UNIX) Link with object library lib<name>. (UNIX) Add <directory> to the list of directories containing object-library routines.
-D<name>=<value>
-f <<optionsfile>>
-g
-h[elp]
-I<pathname>
-inline
-l<name> -L<directory>
7-21
mbuild
Specify compiler language. <language> can be c or cpp. By default, mbuild determines which compiler (C or C++) to use by inspection of the source files extension. This option overrides that mechanism. This option is necessary when you use an unsupported file extension, or when you pass in all .o files and libraries. No execute mode. Print out any commands that mbuild would execute, but do not actually execute any of them. Do not link against the MATLAB C/C++ Graphics Library (Handle Graphics). Optimize the object code by including the optimization flags listed in the options file. If this option is specified, mbuild appends the value of options file variables ending in OPTIMFLAGS with their corresponding base variable. Note that optimizations are enabled by default, are disabled by the -g option, but are reenabled by -O. Place any generated object, resource, or executable files in the directory <dirname>. Do not combine this option with -output if the -output option gives a full pathname. Create an executable named <resultname>. An appropriate executable extension is automatically appended. Overrides the mbuild default executable naming mechanism.
-n
-nohg
-O
-outdir <dirname>
-output <resultname>
7-22
mbuild
(Windows) Use the regsvr32 program to register the resulting shared library at the end of compilation. The Compiler uses this option whenever it produces a COM wrapper file. Interactively specify the compiler options file to use as default for future invocations of mbuild by placing it in
<UserProfile>\Application Data\MathWorks\ MATLAB\R13 (Windows) or $HOME/.matlab/R13
-setup
(UNIX). When this option is specified, no other command line input is accepted.
-U<name>
Remove any initial definition of the C preprocessor symbol <name>. (Inverse of the -D option.) Verbose; Print the values for important internal variables after the options file is processed and all command line arguments are considered. Prints each compile step and final link step fully evaluated to see which options and files were used. Very useful for debugging.
-v
7-23
mbuild
(UNIX) Override an options file variable for variable <name>. If <value> contains spaces, enclose it in single quotes, e.g., CFLAGS='opt1 opt2'. The definition, <def>, can reference other variables defined in the options file. To reference a variable in the options file, prepend the variable name with a $, e.g., CFLAGS='$CFLAGS opt2'. Override an options file variable for variable <name>. If <def> contains spaces, enclose it in single quotes, e.g., CFLAGS='opt1 opt2'. The definition, <def>, can reference other variables defined in the options file. To reference a variable in the options file, prepend the variable name with a $, e.g., CFLAGS='$CFLAGS opt2'.
<name>#<value>
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-24
mcc
7mcc
mcc is the MATLAB command that invokes the MATLAB Compiler. You can issue the mcc command either from the MATLAB command prompt (MATLAB
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 mcc -mA full myfun % Options listed separately % 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-25
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. Table 7-2, Macro Options, shows the relationship between the macro approach to accomplish a standard compilation and the multioption alternative.
Table 7-2: Macro Options Macro Option Bundle File Creates Option Equivalence
Translate M to C/C++ | Function Wrapper | | Target Language | | | Output Stage | | | | Helper Functions | | | | | | | | | | M-File Library | | | | | |
-m
macro_option_m
Stand-alone C application Stand-alone C++ application MEX-function Simulink S-function Enable debug
-t -W main
-L C
-T link:exe -h
libmmfile.mlib
-p
macro_option_p
-t -W main
-L Cpp -T link:exe -h
libmmfile.mlib
-x -S
macro_option_x macro_option_S
-t -W mex
-L C
-t -W simulink -L C
-g
macro_option_g
-G -A debugline:on -O none
Understanding a Macro Option. The -m option tells the Compiler to produce a stand-alone C application. The -m macro is equivalent to the series of options -t -W main -L C -T link:exe -h libmmfile.mlib
7-26
mcc
Table 7-3, -m Macro, shows the options that compose the -m macro and the information that they provide to the Compiler.
Table 7-3: -m Macro Option -t -W main Function
Translate M code to C/C++ code. Produce a wrapper file suitable for a stand-alone application. Generate C code as the target language. Create an executable as the output. Automatically, find and compile helper functions included in the source M-file. Link to this shared library whenever necessary.
-L C -T link:exe -h
libmmfile.mlib
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-27
mcc
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.
directory you want on the default path, and name this file mccpath. (Alternately, you can call the mccsavepath M-function from MATLAB to create an mccpath file.)
2 Place this file in your preferences directory. To do so, run the following
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-28
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.
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
would be equivalent to
7-29
mcc
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.
Note The Compiler produces a warning (specified_file_mismatch) if a file with a full pathname is included on the command line and it finds it somewhere else.
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
mcc -x watson bell
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-30
mcc
Macros
The macro options simplify the compilation process by combining the most common compilation tasks into single options. These options affect the actual code that the Compiler generates. For example, -L specifies the target language as either C or C++. These options provide information to the Compiler such as where to put (-d) and find (-I) particular files. These options provide information for the mbuild and/or mex scripts.
Code Generation
mbuild/mex
The remainder of this reference page is subdivided into sections that correspond to the Compiler option categories. Each section provides a full description of all of the options in the category.
Macro Options
The macro options provide a simplified way to accomplish basic compilation tasks.
-g (Debug). This option is a macro that is equivalent to -G -A debugline:on -O none
or
-B macro_option_g
7-31
mcc
In addition to the -G option, the -g option includes the -A debugline:on option. This will have an impact on performance of the generated code. If you want to have debugging information, but do not want the performance degradation associated with the debug line information, use -g -A debugline:off. The -g option also includes the -O none option, causing all compiler optimizations to be turned off. If you want to have some optimizations on, you may specify them after the debug option.
-m (Stand-Alone C). Produce a stand-alone C application. It includes helper functions by default (-h), and then generates a stand-alone C wrapper (-W main). In the final stage, this option compiles your code into a stand-alone executable and links it to the MATLAB C/C++ Math Library (-T link:exe). For example, to translate an M-file named mymfile.m into C and to create a stand-alone executable that can be run without MATLAB, use mcc -m mymfile
or
-B macro_option_m -p (Stand-Alone C++). Produce a stand-alone C++ application. It includes helper functions by default (-h), and then generates a stand-alone C++ wrapper (-W main). In the final stage, this option compiles your code into a stand-alone executable and links it to the MATLAB C/C++ Math Library (-T link:exe). For example, to translate an M-file named mymfile.m into C++ and to create a
or
-B macro_option_p
7-32
mcc
the Simulink S-Function block. For example, to translate an M-file named mymfile.m into C and to create the corresponding Simulink S-function using dynamically sized inputs and outputs, use
mcc -S mymfile
or
-B macro_option_s -x (MEX-Function). Produce a MEX-function. For example, to translate an M-file named mymfile.m into C and to create the corresponding MEX-file that can be called directly from MATLAB, use mcc -x mymfile
or
-B macro_option_x
Bundle Files
-B ccom (C COM Object). Produce a C COM object. The -B ccom option is equivalent to the series of options -t -W com:<component_name>,<class_name>,<version> -T link:lib -h libmmfile.mlib -i -B cexcel (C Excel COM Object). Produce a C Excel COM object. The -B cexcel option is equivalent to the series of options -B excel:<component_name>,<class_name>,<version> -T link:lib -h libmmfile.mlib -b -i -B csglcom (C Handle Graphics COM Object). Produce a C COM object that uses Handle Graphics. The -B csglcom option is equivalent to the series of options
7-33
mcc
-B sgl -t -W comhg:<component_name>,<class_name>,<version> -T link:lib -h libmmfile.mlib -i -B csglexcel (C Handle Graphics Excel COM Object). Produce a C Excel COM object that uses Handle Graphics. The -B csglexcel option is equivalent to the series of options -B sgl -t -W excelhg:<component_name>,<class_name>,<version> -T link:lib -h libmmfile.mlib -b -i -B csglsharedlib (C Handle Graphics Shared Library). Produce a C shared library that uses Handle Graphics. The -B csglsharedlib option is equivalent to the series of options -t -W libhg:<shared_library_name> -T link:lib -h libmmfile.mlib libmwsglm.mlib -B cppcom (C++ COM Object). Produce a C++ COM object. The -B cppcom option is equivalent to the series of options -B ccom:<component_name>,<class_name>,<version> -L cpp -B cppexcel (C++ Excel COM Object). Produce a C++ Excel COM object. The -B cppexcel option is equivalent to the series of options -B cexcel:<component_name>,<class_name>,<version> -L cpp -B cppsglcom (C++ Handle Graphics COM Object). Produce a C++ COM object that uses Handle Graphics. The -B cppsglcom option is equivalent to the series of options -B csglcom:<component_name>,<class_name>,<version> -L cpp -B cppsglexcel (C++ Handle Graphics Excel COM Object). Produce a C++ Excel COM object that uses Handle Graphics. The -B cppsglexcel option is equivalent to the series of options -B csglexcel:<component_name>,<class_name>,<version> -L cpp -B cpplib (C++ Library). Produce a C++ library. The -B cpplib option is
7-34
mcc
uses Handle Graphics. The -B sgl option is equivalent to the series of options
-m -W mainhg libmwsglm.mlib -B sglcpp (Stand-Alone C++ Graphics Library). Produce a stand-alone C++
application that uses Handle Graphics. The -B sglcpp option is equivalent to the series of options
-p -W mainhg libmwsglm.mlib
M-file code and/or comment inclusion (annotation) #line preprocessor directive inclusion (line) Whether error messages report the source file and line number (debugline) To control the M-file code that is included in the generated C/C++ source, use
mcc -A annotation:type
7-35
mcc
Table 7-5, Code/Comment Annotation Options, shows the available annotation options.
Table 7-5: Code/Comment Annotation Options Type all Description
Provides the complete source of the M-file interleaved with the generated C/C++ source. The default is all. Provides all of the comments from the M-file interleaved with the generated C/C++ source. No comments or code from the M-file are added to code.
comments
none
To control the #line preprocessor directives that are included in the generated C/C++ source, use
mcc -A line:setting
Table 7-6, Line Annotation Options, shows the available #line directive settings.
Table 7-6: Line Annotation Options Setting on Description
Adds #line preprocessor directives to the generated C/C++ source code to enable source M-file debugging. Note: The page width option is ignored when this is on. Adds no #line preprocessor directives to the generated C/C++ source code. The default is off.
off
To control if run-time error messages report the source file and line number, use
mcc -A debugline:on
7-36
mcc
Table 7-7, Run-Time Error Annotation Options, shows the available debugline directive settings.
Table 7-7: Run-Time Error Annotation Options Setting on Description
Specifies the presence of source file and line number information in run-time error messages. Specifies no source file and line number information in run-time error messages. The default is off.
off
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
To include the standard #line preprocessor directives in your generated C/C++ source code as well as source file and line number information in your run-time error messages, use
mcc -A line:on -A debugline:on -F <option> (Formatting). Control the formatting of the generated code. Table 7-8, Formatting Options, shows the available options. Table 7-8: Formatting Options <Option> list Description
Generates a table of all the available formatting options. Sets the number of spaces of indentation for all expressions to n, where n is an integer. The default indent is 4.
expression-indent:n
7-37
mcc
Sets maximum width of generated code to n, where n is an integer. The default width is 80. Sets the number of spaces of indentation for all statements to n, where n is an integer. The default indent is 2.
statement-indent:n
-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 -L <language> (Target Language). Specify the target language of the compilation. Possible values for language are C or Cpp. The default is C. Note that these values are case insensitive. -O <option> (Optimization Options). Optimize 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. Table 7-9, Optimization Options, shows the available options. Table 7-9: Optimization Options <Option> -O list -O all Description
Lists all available optimizations. Turns on all optimizations; all is the default. Equivalent to -B opt_bundle_all.
7-38
mcc
Turns off all optimizations. Equivalent to -B opt_bundle_none. Enables or disables individual optimizations, where <opt option> is: array_indexing fold_mxarrays fold_non_scalar_mxarrays fold_scalar_mxarrays optimize_conditionals optimize_integer_for_loops percolate_simple_types speculate
-O <opt option>:[on|off]
-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. (Use this with the -S option.) -W <type> (Function Wrapper). Control the generation of function wrappers for a collection of Compiler-generated M-files. You provide a list of functions and the Compiler generates the wrapper functions and any appropriate global variable definitions. Table 7-10, Function Wrapper Types, shows the valid options. Table 7-10: Function Wrapper Types <Type> mex main simulink Description
Produces a mexFunction() interface. Produces a POSIX shell main() function. Produces a Simulink C MEX S-function interface.
7-39
mcc
Produces an initialization and termination function for use when compiling this Compiler-generated code into a larger application. This option also produces a header file containing prototypes for all public functions in all M-files specified. <string> becomes the base (file) name for the generated C/C++ and header file. Creates a .exports file that contains all nonstatic function names. Produces a COM object from MATLAB M-files. Produces a Handle Graphics COM object from MATLAB M-files. Produces a COM object from MATLAB M-files. Produces a Handle Graphics COM object from MATLAB M-files. Does not produce a wrapper file. The default is none.
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.
7-40
mcc
-y (Number of Outputs). Provide 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. (Use this with the -S option.)
options and corresponding arguments and/or other filenames. The file may contain other -B options. A bundle file can include replacement parameters for Compiler options that accept names and version numbers. For example, there is a bundle file for C shared libraries, csharedlib, that consists of
-t -W lib:%1% -T link:lib -h libmmfile.mlib
To invoke the Compiler to produce a C shared library using this bundle, you would use
mcc -B csharedlib:mysharedlib <f1>,<f2>,...
In general, each %n% in the bundle file will be replaced with the corresponding option specified to the bundle file. Use %% to include a % character. It is an error to have too many or too few options to the bundle file. You can place options that you always set in an mccstartup file. For more information, see Setting Up Default Options on page 7-27.
7-41
mcc
Note You can use the -B option with a replacement expression as is at the DOS or UNIX prompt. To use -B with a replacement expression at the MATLAB prompt, you must enclose the expression that follows the -B in single quotation marks. For example:
>>mcc -B 'csharedlib:libtimefun' weekday data tic calendar toc
7-42
mcc
Contents -W main -L C -t -T link:exe -h libmmfile.mlib -W main -L cpp -t -T link:exe -h libmmfile.mlib -W simulink -L C -t -T link:mex libmatlbmx.mlib -W mex -L C -t -T link:mexlibrary libmatlbmx.mlib -O -O -O -O -O -O -O -O -O -O -O fold_scalar_mxarrays:on fold_non_scalar_mxarrays:on optimize_integer_for_loops:on array_indexing:on optimize_conditionals:on fold_scalar_mxarrays:off fold_non_scalar_mxarrays:off optimize_integer_for_loops:off array_indexing:off optimize_conditionals:off speculate:off
opt_bundle_none
-t -L P -m -W mainhg libmwsglm.mlib -p -W mainhg libmwsglm.mlib -c (C Code Only). When used with a macro option, 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.
7-43
mcc
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 (Include Exported Interfaces). Cause the Compiler to include only the M-files that
are specified on the command line as exported interfaces. If additional M-files are compiled as a result of being located by the -h option, they are not included in the exported interface that is produced by the MATLAB Compiler.
-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>
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.
-o <outputfile>. Specify the basename of the final executable output (stand-alone applications only) of the Compiler. A suitable, possibly platform-dependent, extension is added to the specified basename (e.g., .exe for PC stand-alone applications).
Note You cannot use this option to specify a different name for a MEX-file.
C/C++ files.
-T <target> (Output Stage). Specify the desired output stage. Table 7-11, Output Stage Options, gives the possible values of target.
7-44
mcc
Translates M-files to C/C++ files and generates a wrapper file. The default is codegen. Same as codegen plus compiles C/C++ files to object form suitable for linking into a Simulink S-function MEX-file. Same as codegen plus compiles C/C++ files to object form suitable for linking into an ordinary (non-S-function) MEX-file. Same as codegen plus compiles C/C++ files to object form suitable for linking into a standalone executable. Same as codegen plus compiles C/C++ files to object form suitable for linking into a shared library/DLL. Same as compile:mex plus links object files into a Simulink S-function MEX-file. Same as compile:mexlibrary plus links object files into an ordinary (non-S-function) MEX-file. Same as compile:exe plus links object files into a standalone executable. Same as compile:lib plus links object files into a shared library/DLL.
compile:mex
compile:mexlibrary
compile:exe
compile:lib
link:mex
link:mexlibrary
link:exe
link: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-45
mcc
The Compiler version number The source filenames as they are processed The names of the generated output files as they are created The invocation of mex or mbuild The -v option passes the -v option to mex or mbuild and displays information about mex or mbuild.
-w (Warning). Display warning messages. Table 7-12, Warning Option, shows the various ways you can use the -w option. Table 7-12: Warning Option Syntax Description
(no -w option)
-w list
Default; displays only serious warnings. Generates a table that maps <string> to warning message for use with enable, disable, and error. Appendix B, Error and Warning Messages lists the same information. Enables complete warnings. Disables specific warning associated with <string>. Appendix B, Error and Warning Messages lists the valid <string> values. Leave off the optional :<string> to apply the disable action to all warnings.
-w -w disable[:<string>]
7-46
mcc
Enables specific warning associated with <string>. Appendix B, Error and Warning Messages lists the valid <string> values. Leave off the optional :<string> to apply the enable action to all warnings. Treats specific warning associated with <string> as error. Leave off the optional :<string> to apply the error action to all warnings.
-w error[:<string>]
-Y <license.dat File>. Use license information in license.dat file when checking out a Compiler license.
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 in the MATLAB documentation for more information about using this option with the mex script.
Note Although this option works as documented, we suggest 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".
7-47
mcc
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.
Examples
Make a C translation and a Simulink S-function for myfun.m (using dynamically sized inputs and outputs):
mcc -S myfun
Make a C translation and a Simulink S-function for myfun.m (explicitly calling for one input and two outputs):
mcc -S -u 1 -y 2 myfun
Make a C translation and stand-alone executable for myfun.m. Look for myfun.m in the /files/source directory, and put the resulting C files and executable in the /files/target directory:
mcc -m -I /files/source -d /files/target myfun
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-48
mcc
mcc -t -L C myfun
Make a C translation and a stand-alone executable from myfun1.m and myfun2.m (using one mcc call):
mcc -m myfun1 myfun2
Make a C translation and a stand-alone executable from myfun1.m and myfun2.m (by generating each output file with a separate mcc call):
mcc mcc mcc mcc mcc mcc mcc -t -t -W -T -T -T -T -L C myfun1 % Yields myfun1.c -L C myfun2 % Yields myfun2.c main -L C myfun1 myfun2 % Yields myfun1_main.c compile:exe myfun1.c % Yields myfun1.o compile:exe myfun2.c % Yields myfun2.o compile:exe myfun1_main.c % Yields myfun1_main.o link:exe myfun1.o myfun2.o myfun1_main.o
Note On PCs, filenames ending with .o above would actually end with .obj.
7-49
mcc
7-50
A
MATLAB Compiler Quick Reference
This appendix summarizes the Compiler options and provides brief descriptions of how to perform common tasks. Common Uses of the Compiler (p. A-2) mcc (p. A-4) Brief summary of how to use the Compiler Quick reference table of Compiler options
A-2
Create a C++ Library. To create a C++ library, use mcc -p -W lib:libfoo -T compile:lib foo.m Create a C Shared Library. To create a C shared library that performs specialized calculations that you can call from your own programs, use mcc -W lib:mylib -L C -t -T link:lib -h Function1 Function2 Create MATLAB P-Code. To translate an M-file named mymfile.m into MATLAB
P-code, use
mcc -B pcode mymfile
Note You can add the -g option to any of these for debugging purposes.
A-3
mcc
Bold entries in the Comment/Options column indicate default values.
Table A-1: mcc Quick Reference Option A annotation:type Description Comment/Options type = all comments none on off
Controls M-file code/comment inclusion in generated C/C++ source Controls the inclusion of source filename and line numbers in run-time error messages Controls the #line preprocessor directives included in the generated C/C++ source Generates a Visual Basic file containing the Microsoft Excel Formula Function interface to the Compiler-generated COM object. Replaces -B filename on the mcc command line with the contents of filename When used with a macro option, generates C code only Places output in specified
directory
A debugline:setting
setting =
A line:setting
setting =
on off
B filename
The file should contain only mcc command line options. Overrides -T option; equivalent to
-T codegen
d directory
f filename
A-4
mcc
Table A-1: mcc Quick Reference (Continued) Option F option Description Comment/Options option = list expression-indent:n page-width:n statement-indent:n
Generates debugging information Debug only. Simply turn debugging on, so debugging symbol information is included. Compiles helper functions Causes Compiler to include only M-files specified on the command line as exported interfaces. Adds new directory to path Generates code that reports file and line numbers on run-time errors Specifies output target language Macro to generate a C stand-alone application Passes string to mex or
mbuild
Equivalent to
-G -A debugline:on -O none
h i
I directory l
Equivalent to
-A debugline:on
L language
language =
C Cpp
Equivalent to
-W main -L C -t -T link:exe -h libmmfile.mlib
M string
o outputfile
A-5
Table A-1: mcc Quick Reference (Continued) Option O O O O option:[on|off] all none list Description Comment/Options option = array_indexing fold_mxarrays fold_non_scalar_mxarrays fold_scalar_mxarrays optimize_conditionals optimize_integer_for_loops percolate_simple_types speculate
Macro to generate a C++ stand-alone application Macro to generate Simulink S-function Translates M code to C/C++ code Specifies output stage
Equivalent to
-W main -L Cpp -t -T link:exe -h libmmfile.mlib
Equivalent to
-W simulink -L C -t -T link:mex libmatlbmx.mlib
T target
target =
u number
Specifies number of inputs for Simulink S-function Verbose; Displays compilation steps
A-6
mcc
Table A-1: mcc Quick Reference (Continued) Option w option Description Comment/Options option = list level level:string where level = disable enable error No w option displays only serious
warnings (default).
W type
Macro to generate MEX-function Specifies number of outputs for Simulink S-function Uses licensefile when checking out a Compiler license Specifies path for library and include files Displays help message
Equivalent to
-W mex -L C -t -T link:mexlibrary libmatlbmx.mlib
y number
Y licensefile
z path
A-7
A-8
B
Error and Warning Messages
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. Use this reference to Confirm that an error has been reported Determine possible causes for an error Determine possible ways to correct an error 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 support@mathworks.com. Compile-Time Errors (p. B-2) Warning Messages (p. B-11) Run-Time Errors (p. B-18) Error messages generated at compile time User-controlled warnings generated by the Compiler Errors generated by the Compiler into your code
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 recompile M-file "filename" because it is already in library "libraryname". A procedure already exists in a library that has the same name as the M-file that is being compiled. For example: mcc -x sin.m % Incorrect
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
Verify that the file exists and that the path includes the files 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 on page 3-10.
Error: File: filename Line: # Column: # != is not a MATLAB operator. Use ~= instead. Use
B-2
Compile-Time Errors
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 if x = y, z = w; end % Correct % Incorrect
Error: File: filename Line: # Column: # A variable cannot be made storageclass1 after being used as a storageclass2. You cannot change a variables 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
B-3
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) [3] = myfunc(a) % Correct % 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
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) [x, y] = f.z % Correct % Incorrect
Error: File: filename Line: # Column: # Invalid multiple left-hand-side assignment. For
Error: File: filename Line: # Column: # MATLAB assignment cannot be nested. You cannot
B-4
Compile-Time Errors
Error: File: filename Line: # Column: # Missing variable or function. An illegal name was
Error: File: filename Line: # Column: # Only functions can return multiple values. In this
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; [x, y] = 1:10; % Correct % Incorrect
B-5
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. 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.
B-6
Compile-Time Errors
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') mcc('-A none') % Correct % Incorrect
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 MATLAB Compiler Option Flags on page 7-31 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 mcc -m -D german sample.m % Correct % 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 mcc -L COBOL % Correct % 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.
B-7
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 on page 7-31 or type mcc -? at the command prompt. 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
cannot be combined.
-A, -B, -d, -f, -F, -I, -L, -M, -o, -T, -u, -W, -x, -y, -Y, -z
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 an output file(s). See MATLAB Compiler Option Flags on page 7-31 or type mcc -? at the command prompt for more information.
B-8
Compile-Time Errors
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. 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 mcc -V2.0L Cpp % Correct % Incorrect
Error: The -optionname option requires an argument (e.g. "proper_example_usage"). You have incorrectly used a Compiler option. For more information about Compiler options, see MATLAB Compiler Option Flags on page 7-31 or type mcc -? at the command prompt. Error: This version of MCC does not support the creation of C++ MEX code. You cannot
B-9
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 on page 7-31 or type mcc -? at the command prompt. Error: Unknown typesetting option: optionname. The valid typesetting options available with -F are expression-indent:n, list, page-width, and statement-indent:n. Error: Unknown warning enable/disable string: warningstring. -w enable:, -w disable:, and -w error: require you to use one of the warning string
B-10
Warning Messages
Warning Messages
This section lists the warning messages that the MATLAB Compiler 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 on page 7-31.
Warning: (PM) Warning: message. (path_manager_warning) The path manager can experience file I/O problems when reading the directory structure (permissions). Warning: (PMI): message. (path_manager_inform) This is an informational path
manager message.
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-11
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
(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: # References to "variablename" will produce a run-time error because it is an undefined function or variable.
(undefined_variable_or_unknown_function) This warning appears if you refer to a variable but never provide it with a value. The most likely cause of this warning is when you call a function that is not on the path or it is a method function.
Note Inline objects are not supported in this release and will produce this warning when used.
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
B-12
Warning Messages
will be called through an feval call. This is used so that the -h option will automatically compile the selected functions.
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
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-13
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
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
B-14
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,
statement.
Warning: File: filename Line: # Column: # Unrecognized Compiler pragma "pragmaname".
(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-15
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: No M-function source available for "functionname", assuming function [varargout] = functionname(varargin) NOTE: This will produce a link error in stand-alone code unless you provide a handwritten definition for this function. (using_stub_function) The Compiler found a .p or .mex version of the function
(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-16
Warning Messages
Warning: The name of a shared library should begin with the letters "lib". "libraryname" doesnt. (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 cant use the -V2.0 option. For more information about Compiler options, see MATLAB Compiler Option Flags on page 7-31.
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 on page 5-5.
B-17
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 MATLAB Compiler Option Flags on page 7-31.
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
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-18
Run-Time Errors
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-19
B-20
Index
Symbols
#line directives 5-42 %#external 7-5 %#function 7-6 %#mex 7-7 %#mex pragma 7-7 .cshrc 4-11 .DEF file 4-22 -B cppexcel option flag 7-34 -B cpplib option flag 7-34 -B cppsglcom option flag 7-34 -B cppsglexcel option flag 7-34 -B csglcom option flag 7-33 -B csglexcel option flag 7-34 -B csglsharedlib option flag 7-34 -B csharedlib option flag 7-35 -b option 7-41
A
-A option flag 7-35
-B option flag 7-41 -B pcode option flag 7-35 -B sgl option flag 7-35 -B sglcpp option flag 7-35 bcc53opts.bat 2-16 bcc54opts.bat 2-16 bcc55opts.bat 2-16 bcc56opts.bat 2-16
add-in MATLAB for Visual Studio 4-23 adding directory to path -I option flag 7-44 algorithm hiding 1-16 annotating -A option flag 7-35 code 5-40, 7-35 output 7-35 ANSI compiler installing on Microsoft Windows 2-17 installing on UNIX 2-7 application POSIX main 5-22 application coding with M-files and C/C++ files 4-42 M-files only 4-36 array_indexing optimization 6-6 axes objects 1-21
Borland compiler 2-14 environment variable 2-26 bundle file option 5-25, 7-41 bundle files 7-42 bundling compiler options -B option flag 7-41
C
-c option flag 7-43
C compilers supported on PCs 2-14 supported on UNIX 2-4 generating 7-43 interfacing to M-code 5-46 shared library wrapper 5-24
B
-B ccom option flag 7-33 -B cexcel option flag 7-33 -B cppcom option flag 7-34
I-1
Index
C++ compilers supported on PCs 2-14 supported on UNIX 2-4 interfacing to M-code 5-46 library wrapper 5-28 required features templates 4-6 callback problems, fixing 1-20 callback strings searching M-files for 1-21 changing compiler on PC 2-20 changing license file -Y option flag 7-47 code controlling #line directives 5-42 controlling comments in 5-40 controlling run-time error information 5-44 hiding 1-16 porting 5-34 setting indentation 5-35 setting width 5-35 COM component wrapper 5-29 COM object building 4-31 files created 5-30 interface 4-31, 4-32 support 4-31 supported compilers 4-31, 4-32 command duality 5-22 compiler C++ requirements 4-6 changing default on PC 4-18 changing default on UNIX 4-8 changing on PC 2-20 choosing on PC 4-17
choosing on UNIX 4-8 MIDL 4-31, 4-32 resource 4-31, 4-32 selecting on PC 2-19 Compiler 2.1. See MATLAB Compiler. Compiler 2.3. See MATLAB Compiler. Compiler library on UNIX 4-11 Compiler. See MATLAB Compiler. compiling complete syntactic details 7-257-49 embedded M-file 7-30 getting started 3-13-5 compopts.bat 2-16 configuration problems 2-25 conflicting options resolving 7-29 conventions in our documentation (table) xii creating MEX-file 3-3 .cshrc 4-11
D
-d option flag 7-43
debugging -G option flag 7-47 line numbers of errors 7-38 debugging symbol information 7-31 debugline setting 5-44 Digital Fortran 2-26 Digital UNIX C++ shared libraries 4-13 Fortran shared libraries 4-13 directory user profile 2-16 DLL. See shared library.
I-2
Index
E
embedded M-file 7-30 environment variable 2-26 library path 4-11 out of environment space on Windows 2-25 error messages Compiler B-1 compile-time B-2B-10 internal error B-1 run-time B-18B-19 warnings B-11B-17 errors getting line numbers of 7-38 Excel plug-in building 4-32 executables. See wrapper file. export list 5-24 exported interfaces including 7-44 %#external 5-46, 7-5
F
-F option flag 5-35, 7-37 -f option flag 7-47
interface function 5-11, 5-16 feval pragma 7-5, 7-6 figure objects 1-21 file license.dat 2-6, 2-17 mccpath 7-28
mlib 5-24, 5-26 wrapper 1-9 fold_mxarrays optimization 6-5 fold_non_scalar_mxarrays optimization 6-4 fold_scalar_mxarrays optimization 6-4 folding 6-4 formatting code 5-35 -F option flag 7-37 listing all options 5-35 setting indentation 5-37 setting page width 5-35 Fortran 2-26 full pathnames handling 7-29 %#function 5-48, 7-6 function calling from M-code 5-46 comparison to scripts 3-10 compiling method 5-5 private 5-5 duality 5-22 feval interface 5-11, 5-16 hand-written implementation version 5-46 helper 4-41 implementation version 5-11 interface 5-11 mangled name 5-29 nargout interface 5-13, 5-18 normal interface 5-13, 5-17 unsupported in stand-alone mode 1-19 void interface 5-15, 5-20 wrapper 5-21 -W option flag 7-39 function M-file 3-10
I-3
Index
G
-G option flag 7-47 -g option flag 7-31 gasket.m 3-2 gcc compiler 2-4 generated Compiler files 5-3 generating P-code 7-35 graphics applications trouble starting 4-28
verify from DOS prompt 2-23 verify from MATLAB prompt 2-23 UNIX 2-4 verify from MATLAB prompt 2-11 verify from UNIX prompt 2-11 integrated development environment, using 4-23 interface function 5-11 interfacing M-code to C/C++ code 5-46 internal error B-1 invoking MEX-files 3-4
H
-h option flag 7-43
Handle Graphics Callback property 1-21 objects 1-21 header file C example 5-8 C++ example 5-9 helper functions -h option 7-43 in stand-alone applications 4-41 hiding code 1-16
L
-L option flag 7-38 -l option flag 7-38 lasterr function 5-45 lccopts.bat 2-16 LD_LIBRARY_PATH
I
-i option 7-44 -I option flag 7-44
IDE, using an 4-23 indentation setting 5-37 inputs dynamically sized 3-7 setting number 3-8 installation Microsoft Windows 2-13 PC 2-14
run-time libraries 4-28 library path 4-11 shared locating on PC 4-22 locating on UNIX 4-11 shared C 1-16 static C++ 1-16 wrapper 5-28 libtbx 1-17 license problem 1-8, 2-17, 2-27, 4-35 license.dat file 2-6, 2-17 licensing 1-7 limitations PC compilers 2-15 UNIX compilers 2-5
I-4
Index
limitations of MATLAB Compiler 2.0 1-18 built-in functions 1-18 exist 1-18 objects 1-18 script M-file 1-18 #line directives 5-42 line numbers 7-38 Linux 2-4 locating shared libraries on UNIX 4-11
M
-M option flag 7-47 -m option flag 4-37, 7-32
macro option 3-6 -B pcode 7-35 -B sgl 7-35 -B sglcpp 7-35 -m 7-32 -p 7-32 -S 7-33 -x 7-33 main program 5-22 main wrapper 5-22 main.m 4-36 makefile 4-10 mangled function names 5-29 MATLAB add-in for Visual Studio 2-22, 4-23 configuring on Windows 98 4-25 configuring on Windows ME 4-25 MATLAB Compiler annotating code 5-40 capabilities 1-2, 1-14 code produced 1-9 compiling MATLAB-provided M-files 4-40 creating MEX-files 1-9
error messages B-1 executable types 1-9 flags 3-6 formatting code 5-35 generated files 5-3 generated header files 5-8 generated interface functions 5-11 generated wrapper functions 5-21 generating MEX-Files 2-2 generating source files 5-21 getting started 3-1 installing on PC 2-13 UNIX 2-4, 2-6 installing on Microsoft Windows 2-17 license 1-7 limitations 1-18 macro 7-26 new features 1-4, 1-5 options 3-6, 7-317-49 options summarized A-4 setting path in stand-alone mode 7-28 Simulink S-function output 7-33 Simulink-specific options 3-7 supported executable types 5-21 syntax 7-25 system requirements Microsoft Windows 2-13 UNIX 2-4 troubleshooting 2-27, 4-35 verbose output 7-46 warning messages B-1 warnings output 7-46 why compile M-files? 1-16 MATLAB interpreter 1-3 running a MEX-file 1-9
I-5
Index
MATLAB libraries M-file Math 4-40, 7-44 MATLAB plug-ins. See MEX wrapper. Matrix data type 1-17 mbchar 7-8 mbcharscalar 7-9 mbcharvector 7-10 mbint 7-11 mbintscalar 7-13 mbintvector 7-14 mbreal 7-15 mbrealscalar 7-16 mbrealvector 7-17 mbscalar 7-18 mbuild 4-6 options 7-20 overriding language on PC 4-16 UNIX 4-7 -regsvr option 5-32 -setup option 4-18 PC 4-18 UNIX 4-8 troubleshooting 4-33 verbose option PC 4-20 UNIX 4-10 verifying PC 4-22 UNIX 4-11 mbuild script PC options 4-23 UNIX options 4-13 mbvector 7-19 mcc 7-25 Compiler 2.3 options A-4 mccpath file 7-28
MCCSAVEPATH 7-28 mccstartup 7-27 method directory 5-5 method function compiling 5-5 %#mex 5-49, 7-7 mex
configuring on PC 2-19 overview 1-9 suppressing invocation of 7-43 verifying on Microsoft Windows 2-22 on UNIX 2-10 MEX wrapper 1-9, 5-22 MEX-file bus error 2-25 comparison to stand-alone applications 4-2 compatibility 1-9 computation error 2-25 configuring 2-2 creating on UNIX 2-9 example of creating 3-3 extension Microsoft Windows 2-22 UNIX 2-10 for code hiding 1-16 generating with MATLAB Compiler 2-2 invoking 3-4 precedence 3-4 problems 2-252-26 segmentation error 2-25 timing 3-4 troubleshooting 2-25 MEX-function 7-33 mexopts.bat 2-16 MFC42.dll 4-28
I-6
Index
M-file compiling embedded 7-30 example gasket.m 3-2 houdini.m 3-10 main.m 4-36 mrank.m 4-36, 4-42 function 3-10 MATLAB-provided 4-40 script 1-18, 3-10 M-files searching for callback strings 1-21 mglinstaller 4-27 mglinstaller.exe 4-28 Microsoft Interface Definition Language (MIDL) compiler 4-31, 4-32 Microsoft Visual C++ 2-14 environment variable 2-26 Microsoft Windows building stand-alone applications 4-15 Compiler installation 2-13 system requirements 2-13 Microsoft Windows registry 2-26 MIDL compiler 4-31, 4-32 mlib files 5-24, 5-26 mrank.m 4-36, 4-42 MSVC. See Microsoft Visual C++. msvc50opts.bat 2-16 msvc60opts.bat 2-16 msvc70opts.bat 2-16 mwMatrix data type 1-17
O
-o option flag 7-44
N
nargout
objects (Handle Graphics) axes 1-21 controls 1-21 figures 1-21 menus 1-21 optimize_conditionals optimization 6-9 optimize_integer_for_loops optimization 6-6 optimizing performance 6-1 conditionals 6-9 disabling all 6-2 enabling all 6-2 enabling selected 6-2 listing all optimizations 6-3 loop simplification 6-6 nonscalar arrays 6-4 -O <optimization option> 6-2 -O all 6-2 -O list 6-3 -O none 6-2 optimization bundles 6-2 scalar arrays 6-4 scalar doubles 6-10 scalars 6-5, 6-10 simple indexing 6-6 when not to optimize 6-1 options 3-6 Compiler 2.3 A-4 macro 3-6 resolving conflicting 7-29 setting default 7-27
I-7
Index
options file combining customized on PC 4-21 locating 2-16 locating on PC 4-16 locating on UNIX 4-8 making changes persist on PC 4-20 UNIX 4-10 modifying on PC 2-21, 4-19 UNIX 4-10 PC 2-16 purpose 4-6 temporarily changing on PC 4-21 UNIX 4-10 UNIX 2-6 out of environment space on Windows 2-25 outputs dynamically sized 3-7 setting number 3-8
PC options file 2-16 running stand-alone application 4-22 supported compilers 2-14 PC compiler limitations 2-15 percolate_simple_types optimization 6-10 personal license password 2-17 PLP 2-17 porting code 5-34 POSIX main application 5-22 POSIX main wrapper 5-22 pragma %#external 5-46, 7-5 %#function 7-6 %#mex 7-7 feval 7-6 private function ambiguous names 5-6 compiling 5-5 problem with license 2-17
P
-p option flag 7-32
R
rank 4-40 registry 2-26 resolving conflicting options 7-29 resource compiler 4-31, 4-32 run-time errors controlling information 5-44
run-time libraries 4-28 path setting in stand-alone mode 7-28 pathnames handling full 7-29
S
-S option flag 3-7, 7-33
I-8
Index
scalar arrays folding 6-4 script M-file 1-18, 3-10 converting to function M-files 3-10 setting default options 7-27 S-function 3-7 generating 3-7 passing inputs 3-7 passing outputs 3-7 shared library 1-16, 4-30 distributing with stand-alone application 4-5 header file 5-24 locating on PC 4-22 locating on UNIX 4-11 UNIX 4-11 wrapper 5-24
SHLIB_PATH
run-time libraries 4-28 Sierpinski Gasket 5-2 Simulink compatible code 3-7 S-function 3-7 -u option flag 7-39 wrapper 5-24 -y option flag 7-41 Simulink S-function output 7-33 restrictions on 3-9 specifying option file -f option flag 7-47 specifying output directory -d option flag 7-43 specifying output file -o option flag 7-44 specifying output stage -T option flag 7-44 speculate optimization 6-10
stand-alone applications 4-1 distributing on PC 4-27 distributing on UNIX 4-13 distributing on Windows 4-26 generating C applications 7-32 generating C++ applications 7-32 helper functions 4-41 overview 4-4 C 1-11 C++ 1-11 process comparison to MEX-files 4-2 restrictions on 1-19 restrictions on Compiler 2.3 1-19 UNIX 4-7 writing your own function 4-40 stand-alone C applications system requirements 4-2 stand-alone C++ applications system requirements 4-3 stand-alone Compiler setting path 7-28 stand-alone graphics applications generating C applications 7-35 generating C++ applications 7-35 startup script 4-11 static library 1-16 supported executables 5-21 system requirements Microsoft Windows 2-13 UNIX 2-4
T
-T option flag 7-44 -t option flag 5-21, 7-44
I-9
Index
templates requirement 4-6 translate M to C -t option flag 7-44 troubleshooting Compiler problems 2-27, 4-35 mbuild problems 4-33 MEX-file problems 2-25 missing functions 1-20 starting stand-alone graphics applications 4-28
add-in 4-23
void interface function 5-15, 5-20
W
-W option flag 7-39 -w option flag 7-46
U
-u option flag 3-8, 7-39
uicontrol objects 1-21 uimenu objects 1-21 UNIX building stand-alone applications 4-7 Compiler installation 2-4 options file 2-6 running stand-alone application 4-12 supported compilers 2-4 system requirements 2-4 UNIX compiler limitations 2-5 unsupported functions in stand-alone mode 1-19 upgrading from Compiler 1.0/1.1 1-17 from Compiler 2.0/2.1/2.2/2.3 1-17 user profile directory 2-16
warning message Compiler B-1 warnings in compiler output 7-46 wat11copts.bat 2-16 Watcom environment variable 2-26 watcopts.bat 2-16 Windows. See Microsoft Windows. wrapper C shared library 5-24 C++ library 5-28 COM component 5-29 main 5-22 MEX 5-22 Simulink S-function 5-24 wrapper file 1-9 MEX 1-9 target types 1-15 wrapper function 5-21
X
-x option flag 7-33
V
-v option flag 7-46
Y
-Y option flag 7-47 -y option flag 3-8, 7-41
verbose compiler output 7-46 Visual Basic file generating 7-41 Visual Studio
Z
-z option flag 7-48
I-10