Mathworks MATLAB COMPILER 4 user guide

MATLAB
®
Compiler™
User’s Guide
4
How to Contact The MathWorks
www.mathworks. comp.soft-sys.matlab Newsgroup www.mathworks.com/contact_TS.html T echnical Support
suggest@mathworks.com Product enhancement suggestions bugs@mathwo doc@mathworks.com Documentation error reports service@mathworks.com Order status, license renewals, passcodes info@mathwo
com
rks.com
rks.com
Bug reports
Sales, prici
ng, and general information
508-647-7000 (Phone)
508-647-7001 (Fax)
The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
®
MATLAB
© COPYRIGHT 1995–20 10 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 MathW orks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation by, for, or through the federal government of the United States. By accepting delivery of the Program or Documentation, the government hereby agrees that this software or documentation qualifies as commercial computer software or commercial computer software documentation as such terms are used or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and govern theuse,modification,reproduction,release,performance,display,anddisclosureoftheProgramand Documentation by the federal government (or other entity acquiring for or through the federal government) and shall supersede any conflicting contractual terms or conditions. If this License fails to meet the government’s needs or is inconsistent in any respect with federal procurement law, the government agrees to return the Program and Docu mentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
The MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Compiler™ User’s Guide
Revision History
September 1995 First printing March 1997 Second printing January 1998 Third printing Revised for Version 1.2 January 1999 Fourth printing Revised for Version 2.0 (Release 11) September 2000 Fifth printing Revised for Version 2.1 (Release 12) October 2001 Online only Revised for Version 2.3 July 2002 Sixth printing Revised for Version 3.0 (Release 13) June 2004 Online only Revised for Version 4.0 (Release 14) August 2004 Online only Revised for Version 4.0.1 (Release 14+) October 2004 Online only Revised for Version 4.1 (Release 14SP1) November 2004 Online only Revised for V ersion 4.1.1 (Release 14SP1+) March 2005 Online only Revised for Version 4.2 (Release 14SP2) September 2005 Online only Revised for Version 4.3 (Release 14SP3) March 2006 Online only Revised for Version 4.4 (Release 2006a) September 2006 Online only Revised for Version 4.5 (Release 2006b) March 2007 Online only Revised for Version 4.6 (Release 2007a) September 2007 Seventh printing Revised for Version 4.7 (Release 2007b) March 2008 Online only Revised for Version 4.8 (Release 2008a) October 2008 Online only Revised for Version 4.9 (Release 2008b) March 2009 Online only Revised for Version 4.10 (Release 2009a) September 2009 Online only Revised for Version 4.11 (Release 2009b) March 2010 Online only n’t Revised for Version 4.13 (Release 2010a)
Getting Started
1
Product Overview ................................. 1-2
What Does This Product Do? When To Use MATLAB When Not To Use MATLAB HowDoIUseThisProduct? How Does This Product Work? What Is The MATLAB Compiler Runtime (MCR)?
®
........................ 1-2
Compiler ................... 1-3
®
Compiler ................ 1-3
......................... 1-4
....................... 1-4
....... 1-6
Contents
Before You Use MATLAB
Understand Your Role in the Application Deployment
Process Verify Your Knowledge Base Install Required Products Select Your C or C++ Compiler with mbuild -setup
Deploying with the Magic Square Example
About This Example Magic Square Example: MATLAB Programmer Tasks Magic Square Example: C/C++ Programmer Tasks
For More Information
........................................ 1-7
®
Compiler ................. 1-7
........................ 1-9
........................... 1-9
...... 1-10
.......... 1-11
............................... 1-11
...... 1-21
.............................. 1-24
Installation and Configuration
2
Before Y o u Install M ATL AB®Compiler .............. 2-2
Install MATLAB Install an ANSI C or C++ Compiler
.................................. 2-2
................... 2-2
... 1-11
Installing MA TLA B
®
Compiler ...................... 2-5
v
Compiler Options ................................. 2-5
On the Windows Operating System On UNIX Operating Systems
................... 2-5
........................ 2-5
Configuring Your Options File with mbuild
What Is mbuild? When Not to Use mbuild Running mbuild Locating and Customizing the Options File
If You Have Installation Problems
.................................. 2-6
............................ 2-6
................................... 2-7
................... 2-12
.......... 2-6
............ 2-9
Writing Deployable MATLAB Code
3
The MATLAB Application Deployment Products ..... 3-2
Building Your Application w ith the Application
Deployment Products and the D e ploy ment Tool
What Is the Difference Between the Deployment Tool and
the mcc Command Line?
How Does MATLAB
Application?
What You Should Know About the Dependency Analysis
Function (depfun) Compiling MEX-Files, DLLs, or Shared Lib rari es The Role of the Component Technology File (CTF
Archive)
....................................... 3-7
®
Compiler Software Build My
.................................... 3-4
............................... 3-5
......................... 3-4
....... 3-6
.... 3-4
vi Contents
Guidelines for Writing Deployable MATLAB Code
Compiled Applications Do No t Process MATLAB Files at
Runtime Do Not Rely on Changing Directory or Path to Control the
Execution of MATLAB Files Use ismcc and isdeployed Functions To Execute
Deployment-Specific Code Paths Gradually Refactor Applications That Depend o n
Noncompilable Functions
....................................... 3-10
....................... 3-11
................... 3-11
......................... 3-12
.... 3-10
Do Not Create or Use Nonconstant Static State
Variables
Working with MATLAB Data Files Using Load and
Save
Using Load/Save Functions to Process MATLAB Data for
............................................ 3-14
Deployed Applications
...................................... 3-12
........................... 3-14
Compilation Tasks
4
Input and Output Files ............................. 4-2
Standalone Executable C Shared Library C++ Shared Library Macintosh 64 (Maci64)
Dependency Analysis Function (depfun) and User
Interaction with the Compilation Path
addpath and rmpath in MATLAB Passing -I <directory> on the Command Line Passing -N and -p <directory> on the Command Line
............................. 4-2
.................................. 4-3
............................... 4-5
............................. 4-7
............ 4-8
.................... 4-8
........... 4-8
.... 4-8
Deployment Process
5
Overview ......................................... 5-2
Deploying to Programmers
Steps by the Programmer to Deploy to Programmers What Software Does a Programmer Need? Ensuring Mem ory for Deployed Applications
DeployingtoEndUsers
Steps by the Programmer to Deploy to End Users
......................... 5-3
............. 5-4
........... 5-7
............................ 5-9
....... 5-9
.... 5-3
vii
What Software Does the End User Need? .............. 5-12
Using Relative Paths with Project Files Porting Generated Code to a Different Platform Extracting a CTF Archive Without Executing the
Component Ensuring Mem ory for Deployed Applications
.................................... 5-16
............... 5-15
......... 5-15
........... 5-16
Working with the MCR
About the MATLAB Installing the MCR and MATLAB on the Same Machine Installing Multiple MCRs on One Machine Retrieving MCR Attributes Improving Data Access Using the MCR User Data
Interface Displaying MCR Initialization Start-Up and Completion
Messages For Users
Deploying a Standalone Application on a Network
Drive
MATLAB
Using MATLAB
Services
Reserving Memory for Deployed Applications with
MATLAB Memory Shielding
What Is MAT LAB Memory Shielding and When Should You
Use It? Requirements for Using MATLAB Memory Shielding Invoking MATLAB Memory Shielding for Yo ur Deployed
Application
...................................... 5-23
........................................... 5-39
®
Compiler Deployment Messages ........... 5-40
®
Compiler Generated DLLs in Windows
........................................ 5-41
........................................ 5-42
.................................... 5-43
............................. 5-18
®
Compiler Runtime (MCR) ......... 5-18
............. 5-21
......................... 5-21
............................. 5-37
...................... 5-42
.. 5-19
.... 5-43
viii Contents
Compiler Commands
6
Command O verview ............................... 6-2
Compiler Options
................................. 6-2
Combining Options ................................ 6-2
Conflicting Options on the Command Line Using File Extensions
.............................. 6-3
............. 6-3
Using Macros to Simplify Compilation
Macro Options Working W ith Macro O ptions
Using Path Names
Using Bundle Files
Using Wrapper Files
What Are Wrapper Files? Main File Wrapper C Library Wrapper C++ Library Wrapper
InterfacingMATLABCodetoC/C++Code
Overview Code Proper Return Types From C and C++ Methods CExample C++ Example
Overriding Default CTF Archive Embedding Using the
MCR Component Cache
.................................... 6-5
........................ 6-5
................................. 6-8
................................. 6-9
............................... 6-11
........................... 6-11
................................ 6-11
................................ 6-12
.............................. 6-13
........................................ 6-14
....................................... 6-14
..................................... 6-16
.......................... 6-20
............... 6-5
............ 6-14
.... 6-14
Using Pragmas
Using feval Example: Using %#function
Using mxArray
Script Files
Converting Script MATLAB Files to Function MATLAB
Files
.......................................... 6-25
Including Script Files in Deployed Applications
Compiler Tips
.................................... 6-22
....................................... 6-22
......................... 6-22
.................................... 6-24
....................................... 6-25
......... 6-26
..................................... 6-28
ix
Calling Built-In Functions from C or C++ .............. 6-28
Calling a Function from the Command Line Using MAT-Files in Deployed Applications Compiling a GUI That Contains an Acti veX Co n t rol Debugging MATLAB Deploying Applications That Call the Java Native
Libraries Locating .fig Files in Deployed Applications Blocking Execution of a Console Application That Creates
Figures and Terminating Figures by Force Passing Arguments to and from a Standalone
Application Using Graphical Applications in Shared Library Targets Using the VER Function in a Compiled MATLAB
Application
...................................... 6-30
®
Compiler Generated Executables .. 6-30
.................................... 6-31
.................................... 6-33
............ 6-29
............. 6-29
............ 6-30
........... 6-31
Standalone Applications
7
Introduction ...................................... 7-2
..... 6-29
.. 6-33
x Contents
C Standalone Application Target
Compiling the Application Testing the Application Deploying the Application Running the Application
Mixing MATLAB Files and C or C++
Examples Overview Simple Example Advanced C Example
................................ 7-8
.................................. 7-9
.......................... 7-3
............................. 7-3
.......................... 7-4
............................ 7-6
.............................. 7-13
.................... 7-3
................. 7-8
Libraries
8
Introduction ...................................... 8-2
Addressing mwArrays Above the 2 GB Limit ......... 8-3
C Shared Library Target
C Shared Library Wrapper C Shared Library Example Calling a Shared Library Using C Shared Libraries On a Mac OS X System
C++ Shared Library Target
C++ Shared Library Wrapper C++ Shared Library Example
MATLAB
Functions in the Shared Library Type of Application Structure of Programs That Call Shared Libraries Library In itialization and Termin ation Functions Print and Error Handling Functions Functions Generated from MATLAB Files Retrieving MCR State Information While Using Shared
About Memory Management and Cleanup
Overview Passing mxArrays to Shared Libraries
®
Compiler Generated Interface F unctions .. 8-23
Libraries
...................................... 8-34
........................................ 8-35
........................... 8-4
.......................... 8-4
.......................... 8-4
........................... 8-11
......................... 8-18
........................ 8-18
....................... 8-18
..................... 8-23
................................ 8-23
.................. 8-27
............. 8-29
........... 8-35
................ 8-35
....... 8-17
...... 8-25
....... 8-26
Troubleshooting
9
Introduction ...................................... 9-2
Common Issues
Failure Points and Possible Solutions
How to Use this Section Does the Failure Occur During Compilation? Does the Failure Occur When Testing Your Application?
.................................... 9-3
............... 9-4
............................ 9-4
........... 9-4
.. 9-8
xi
Does the Failure Occur When Deploying the Application to
End Users?
.................................... 9-11
10
mbuild
MATLAB
Deployed Applications
............................................ 9-14
®
Compiler ................................ 9-16
............................. 9-20
Limitations a nd Restrictions
Limitations About What May Be Compiled ........... 10-2
Compiling MATLAB and Toolboxes Fixing Callback Problems: Missing Functions Finding Missing Functions in an MATLAB File Suppressing Warnings on the UNIX System Cannot Use Graphics with the -nojvm Option Cannot Create the Output File No MATLAB File Help for Compiled Functions No MCR Versioning on Mac OS X Older Neural N etw orks Not Deployable with M ATLA B
Compiler ...................................... 10-7
Restrictions on Calling PRINTDLG with Multiple
Arguments in Compiled Mode Compiling a Function with WHICH Does Not Search
Current Working Directory
................... 10-2
.......... 10-3
......... 10-5
........... 10-5
.......... 10-6
...................... 10-6
......... 10-6
.................... 10-6
®
..................... 10-7
....................... 10-8
xii Contents
11
Unsupported F unctions
............................ 10-9
Reference Information
Directories Required for Development and Testing ... 11-2
Overview
........................................ 11-2
Path for Java Development on All Platforms ........... 11-2
Path M odifications Required for Accessibility Windows Settings for Development and Testing UNIX Settings for Development and Testing
........... 11-2
........ 11-3
........... 11-3
12
Directories Required for Run-Time Deployment
General Path Guidelines Path for Java Applications on All Platforms Windows Path for Run-Time Deployment UNIX Paths for Run-Time Deployment
MATLAB
Using MATLAB
Using MCR Installer Command Line Options
Overview Displaying MCR Installer Location and Related
Accessing MCR Installer Command Line Options on
Accessing MCR Installer Command Line Options on UNIX
®
Compiler Licensing ...................... 11-8
®
Compiler Licenses for Development .... 11-8
........................................ 11-9
Information
Windows Systems
and Linux Systems
.................................... 11-9
........................... 11-5
............ 11-5
.............. 11-5
................ 11-6
......... 11-9
............................... 11-10
.............................. 11-12
Function Reference
...... 11-5
Pragmas .......................................... 12-2
Command-Line Tools
API F unctions
..................................... 12-3
.............................. 12-2
xiii
13
A
B
Functions — Alphabetical List
MATLAB®Compiler Quick Reference
Common Uses of MATLAB®Compiler ............... A-2
Create a Standalone Application Create a Library
mcc
............................................... A-4
.................................. A-2
..................... A-2
Using MATLAB®Compiler on UNIX
Overview ......................................... B-2
xiv Contents
Installing MA TLA B
Installing MATLAB Selecting Your gcc Compiler Custom Configuring Your Options File Install X Code from DVD on Maci and Maci64
Building Your UNIX Application
Compiling Your Application with the Deployment Tool Compiling Your Application with t he Command Line
Testing Your UNIX Application
Deploying Your UNIX Application
Installing the MCR on UNIX Performing a Silent Installation of the MCR on Linux and
Mac Using Run Script to Set MCR Paths
.......................................... B-6
®
Compiler on UNIX .............. B-3
®
Compiler ...................... B-3
......................... B-3
................ B-3
.......... B-3
.................... B-4
..................... B-5
................... B-6
........................ B-6
.................. B-6
... B-4
.... B-4
Running Your 64-Bit Mac Application ............... B-7
Overview Installing the Macintosh Application Launcher Preference
Pane Configuring the Installation Area Launching the Application
........................................ B-7
.......................................... B-7
.................... B-7
.......................... B-10
Error a nd Warning Messages
C
About Error and Warning Messages ................. C-2
Compile-Time Errors
Warning Messages
depfun Errors
About depfun Errors MCR/Dispatcher Errors XML Parser Errors depfun-Produced Errors
..................................... C-10
............................... C-3
................................. C-7
............................... C-10
............................ C-10
................................ C-10
............................ C-11
C++ U tility Library Reference
D
Primitive Types ................................... D-2
Utility Classes
mwString Class
About mwString Constructors Methods Operators
..................................... D-3
.................................... D-4
.................................. D-4
..................................... D-4
......................................... D-4
........................................ D-4
xv
mwException Class ................................ D-20
About mwException Constructors Methods Operators
..................................... D-20
......................................... D-20
........................................ D-20
............................... D-20
mwArray Class
About mwArray Constructors Methods Operators Static Methods
......................................... D-29
........................................ D-30
.................................... D-28
................................... D-28
..................................... D-28
.................................... D-31
Index
xvi Contents

Getting Started

“Product Overview” on page 1-2
®
“Before You Use MATLAB
“Deploying with the Magic Square Example” on page 1-11
“For More Information” on page 1-24
Compiler” on page 1-7
1
1 Getting Started

Product Overview

What Does This Product Do?

MATLAB®Compiler™ compiles a MATLAB®application into a standalone application or software compone nt. The act of compiling this code is sometimes referred to as building.
In this section...
“What Does This Product Do?” on page 1-2
“When To Use MATLAB®Compiler” on page 1-3
“When Not To Use MATLAB®Compiler” on page 1-3
“How Do I Use This Product?” on page 1-4
“How Does This Product Work?” on page 1-4
“What Is The MATLAB Compiler Runtime (MCR)?” on page 1-6
1-2
Building with MATLAB Compiler enables you to run your MATLAB application outside the MATLAB environment. It reduces application development time by eliminating the need to translate your code into a different language. If you are building a standalone application, MATLAB Compiler produces an executable for your e nd users. If you integrate into C or C++, MATLAB Compiler provides an interface to use your code as a shared library. If you integrate into other development languages, MATLAB builder products (ava ilable separately) let you packa ge your M ATLAB app lica tions as software components. You are able to use Java classes, .NET components, or Microsoft
For more information, see “The MATLAB Application Deployment Products” on page 3-2.
For more information about how MATLAB Compiler works, see “The MATLAB Deployable MATLAB Code”.
®
Excel®add-ins.
®
Compiler Build Process” on page 1-18 and Chapter 3, “Writing
Product Overview
Note If you are using a non-Windows operating system, “console applications” are refe rred to as “standalon e applications”.

When To Use MATLAB Compiler

Use MATLAB Compiler to:
Deploy C or C++ code that interfaces with MATLAB
Package MATLAB® applications as executables and shared libraries
Distribute royalty-free, standalone executables and software components
Incorporate MATLAB-based algorithmsintoapplications developed using
other languages and technologies
Encrypt and protect MATLAB code

When Not To Use MATLAB Compiler

Do not use MATLAB Compiler and builder products for applications shown on the following table. Instead, use the recommended MathWorks™ product indicated.
To... Use...
Generate readable, efficient, and
embeddable C code from MATLAB code
Generate MEX functions from
MATLAB code for rapid prototyping and verification of gen erated C code within MATLAB
IntegrateMATLABcodeinto
Simulink®
Speed up fixed-point MATLAB code
Generate hardware description
language (HDL) from MATLAB code
Embedded MATLAB Guide
®
User’s
1-3
1 Getting Started
To... Use...
Integrate custom C code into MATLA B
with MEX files
Call MATLAB from C and Fortran
programs
Deploy Java components into enterprise computing environments and to MATLAB users
Deploy .NET and COM components into enterprise computing environments and to MATLAB users
Deploy Excel add-ins to enterprise computing environments and to MATLAB users
MATLAB External Interfaces
MATLAB Guide
MATLAB Builder NE User’s Guide
MATLAB Builder EX User’s Guide
®
Builder™ JA User’s

How Do I Use This Product?

You use MATLAB Compiler by running the Deployment Tool GUI (
deploytool)orexecutingthemcc command from MATLAB.

How Does This Product Work?

MATLAB Compiler readies your application for deployment to enterprise computing environments using a combination of generated applications, libraries, and wrapper files.
1-4
MATLAB Compiler Generated Applications and Libraries
When you package and distribute applications and libraries that MATLAB Compiler gene rate s, you include the MATLAB Compiler Runtime (MCR). You can include a set of supporting files generated by MA TLAB Compiler. You also set the system paths on the target machine so your application finds the MCR and supporting files.
The MCR is an engine for execution of compiled MATLAB code. As such, when a compiled application runs, there is sometimes a delay as the MCR
Product Overview
is initialized. There can be a delay the first time you run the application, although typically less than you experience running on the MATLAB desktop.
An application or library generated by MATLAB Compiler has two parts: a platform-specific binary file and an archive file containing the encrypted MATLAB application and data. An application binary file consists of a main function. By contrast, a library binary consists of multiple functions for exporting.
Wrapper Files
MATLAB Compiler generates wrapper files. These files pr ovide an interface to your MATLAB code when compiled. The wrapper files and MATLAB code are compiled into platform-specific binary files. Wrapper files differ depending on the execution environment.
Limitations and Considerations
Cross-Platform Considerations
If you are considering porting components created with MA TLAB Compiler, note the following:
Only Java components can cross platforms. Exceptions are specified here.
Deployment across a 32-bit/64-bit boundary does not work for anything
except Java™ components. In other words, deploying from 32-bit Windows
XP to 64-bit Windows XP fails, as would deployment from 64-bit Linux
®
to 32-bit Linux. However, deployment from one o perating system type
to another (Windows XP to Windows Vista™, for example) works. The
machines must be the same architecture (32-bit or 64-bit) and meet the
general system requirements of MATLAB. For example, deployment from
32-bit Windows XP to 32-bit Windows Vista works.
Note You can cross 32 to 64 bit boundaries if your MCR version is
compatible with the MATL AB version the component was created with.
®
1-5
1 Getting Started
What Is The MATLA
The MATLAB Compi that enable the e installed vers
You have the op by the Deploym MCR on the Pack self-extrac MCR Installe
ion of MA TLAB .
ting package executable. For more information on the MCR and the
r, see What Is the MCR and How Do I Get It?
ler Runtime is a standalone set of shared libraries
xecution of MATLAB files, even on computers without an
tion to include the MCR with every package generated
ent Tool (
age tab. Install it on target machines by running the
deploytool). Include the MCR by clicking Add
B Compiler Runtime (MCR)?
1-6

Before You Use MATLAB Compiler

In this section...
“Understand Your Role in the Application Deployment Process” on page 1-7
“Verify Your Knowledge Base” on pag e 1-9
“Install Required Products” on page 1-9
“Select Y our C or C++ Compiler with mbuild -setup” on page 1-10

Understand Your Role in the Application Deployment Process

Depending on the size of your organization, you play one role, or many, in the process of successfully deploying a standalone application or shared library.
For example, you analyze user requirements and satisfy them by writing a program in MATLAB code. You can also implement the infrastructure to deploy an application to users in computing environments different from your own. In smaller organizations, you find one person responsible for performing tasks associated with multiple roles. The table Application Deployment Roles, Tasks, and References on page 1-8 describes some of the different MATLAB Compiler roles or jobs. It also describes which tasks you would most like ly performwhen“DeployingwiththeMagicSquareExample”onpage1-11 in this chapter.
Before You Use MATLAB®Compiler™
Note If you are using a non-Windows operating system, “console applications” are refe rred to as “standalon e applications”.
1-7
1 Getting Started

Application Deployment Roles, Tasks, and References

Role Tasks
MATLAB Programmer
Understand
end-user business requirements and the mathematical models they support
Write MATLAB
code.
Build an executable
component with MATLAB tools (usually with support from an IT programmer or Front-End Developer).
Package the
component for distribution to customers.
Pass the packaged
component to the IT programmer or Front-End Developer for rollout and further integration into the end-user environment.
References
“Magic Square Example: MATLAB Programmer Tasks” on page 1-11
1-8
C or C++ Programmer Set the target
computer path so the system can s upport the compiled code at run time.
“Magic Square Example: C/C++ Programmer Tasks” on page 1-21
Before You Use MATLAB®Compiler™
Application Deployment Roles, Tasks, and References (Continued)
Role Tasks
Install the MCR on
target computers by running the MCR Installer.
Ensure that the
final standalone application or library executes reliably in the customer environment.
External user Executes the solution
created by MATLAB and Front-End Developers.
References
Run the deployed application (outside the scope of this document).

Verify Your Knowledge Base

Using the MATLAB Compiler product requires the follo wing knowledge:
If your job function is MATLAB programmer:
- A basic knowledge of MATLAB, and how to work with cell arrays and
structures
If your job function is C or C++ developer:
- Exposure to the C or C++ programming languages
- Procedural or object-oriented programming concepts

Install Required Products

Install the following products to run the example described in this chapter:
MATLAB
MATLAB Compiler
1-9
1 Getting Started
AsupportedCorC++compiler
For more information about product installation and requirements, see Chapter 2, “Installation and Configuration”.

Select Your C or C++ Compiler with mbuild -setup

The first time you use MATLAB Compiler, after starting MATLAB, run the following command:
mbuild -setup
For more information about mbuild -setup,seeChapter2,“Installationand Configuration”.
If you need information about writing MATLAB files, see MATLAB Programming, which is part of MATLAB documentation.
1-10

Deploying with the Magic Square Example

Deploying with the Magic Square Example
In this section...
“About This Example” on page 1-11
“Magic Square Example: MATLAB Programmer Tasks” on page 1-11
“Magic Square Example: C/C++ Programmer Tasks” on page 1-21

About This Example

The examples for MATLAB Compiler are in
matlabroot\extern\examples\compiler.Format labr oot, substitute the
MATLAB root folder on your system. Type name.
The Magic Square example in this section shows you how to:
UseMATLABCompilertocreateand package a simple standalone
application that compiles a MAT LAB file,
matlabroot to see this folder
magicsquare.m
Access the examples provided with MATLAB Compiler.
Note If you are using a non-Windows operating system, “console
applications” are refe rred to as “standalon e applications”.
Command-Line Alternative
The examples use the deploytool GUI, a graphical front-end interface to MATLAB Compiler software. You can perform these tasks using the command-line interface to MATLAB Compiler software. See “Using the Command Line (mcc)” on page 1-16 and the reference information.
mcc reference page for complete

Magic Square Example: MATLAB Programmer Tasks

The MATLAB programmer performs the tasks described in the following table.
1-11
1 Getting Started
MATLAB expert
No IT experience
MATLAB
Programmer
No access to IT systems

Key Tasks for the MATLAB Programmer

Task
Preparetoruntheexampleby copying the MATLAB example files
Reference
“Copying the Example Files” on page 1-13
into a work folder.
TesttheMATLABcodetoensure that it is suitable for deployment.
Create a standalone application or shared library (enca psulating your MATLAB code in a C or C++ class)
“Testing the MATLAB File You Want To Deploy” on page 1-13
“Creating a Deployable Standalone Application or Shared Library” on page 1-14
by running the Build function in
deploytool.
Run the Packaging Tool to bundle your standalone application or
“Packaging Your Deployment
Application (Optional)” on page 1-15 shared library with the additional files you selected.
Develops model
Uses the builder tools to create a component that is given to the business service developer
1-12
Copy the output from the Packaging Tool (the
distrib folder).
“Copy the Package You Created
(Optional)” on page 1-16
TheMagicSquareexampleshowshowtocreate a standalone application, or shared library (
magicsquare), containing the magic class and other files for
application deployment. The class encapsulates a MATLAB function which computes a m agic square.
The client standalone application or shared library converts the array returned by the function to a native array and displays it on the screen. When you run the
magicsquare application from the command line, you pass the
dimension for the magic square as a command-line argument
Deploying with the Magic Square Example
Note The examples for the MATLAB Compiler product reside in
matlabroot\extern\examples\compiler. Thisexampleassumesthatthe
work folder is on dr ive
D:.
Copying the Example Files
Preparetoruntheexamplebycopying needed files into your work area as follows:
1 Navigate to matlabroot\extern\examples\compiler. matlabroot is the
MATLAB root folder (where you installed MATLAB). To find the value of this variable on your system, type prompt.
2 Create a work folder named Work (D:\Work). Create a subfolder in your
Work folder and name it MagicExample (D:\Work\MagicExample). Avoid
using spaces in your folder names, if possible.
matlabroot at a MATLAB command
3 Copy magicsquare.m from matlabroot\extern\examples\compiler to
D:\Work\MagicExample.
4 At the MATLAB command prompt, change your working folder to
D:\Work\MagicExample.
Testing the MATLAB File You Want To Deploy
In this example, you test a MATLAB file (magicsquare.m) containing the predefined MATLAB function comparetotheresultsofthefunctionasadeployablestandaloneapplication or shared library.
1 Using MATLAB, locate and open magicsquare.m.Thisfilehasthe
following:
function m = magicsquare(n) %MAGICSQUARE generates a magic square matrix of the size % specified by the input parameter n.
% Copyright 2003-2007 The MathWorks, Inc.
magic. Testingthefileprovidesabaselineto
1-13
1 Getting Started
if ischar(n)
n=str2num(n); end m = magic(n);
2 At the MATLAB command prom pt, enter magicsquare(5),andviewthe
results. The output appears as follows:
17 24 1 8 15 23 5 7 14 16
4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
Creating a Deployable Standalone Application or Shared Library
You create a deployable standalone application or shared library by using the Deployment Tool GUI to build a wrapper. This wrapper encloses the sample MATLAB code discussed in “Testing the MATLA B File You Want To Deploy” on page 1-13. To run the Magic Square example, use the following information:
1-14
Project Name
File to compile
1 Start MATLAB.
2 Type deploytool at the comman d prompt and press Enter. The
deploytool GUI opens.
3 Create a deployment project using the Deployment Project dialog:
a TypethenameofyourprojectintheName field.
b Enter the location of the project in the Location field. Alternately ,
MagicExample
magicsquare.m
navigate to the location.
c Select the target for the deployment project from the Target drop-down
menu.
d Click OK.
Deploying with the Magic Square Example
Creating
4 On the Build tab:
a C Shared Library Project
Click Add files.
Note You may optionally add supporting files. For examples of these
files, see the
deploytool Help. To add these files, in the Shared Resources
and Helper Files area:
a Click Add files/directories
b Click Open to select the file or files.
5 When
you complete your changes, click the Build button (
).
Packaging Your Deployment Application (Optional)
kaging is bundling the standalone application or shared libraries with
Pac
itional files for end users. Perform this step using the Package tab of
add
loytool
dep
R Installer to a local folder of your choice.
MC
. Alternately, copy the contents of the distrib folder and the
1-15
1 Getting Started
1 On the Package tab, add the MATLAB Compiler Runtime (the MCR) by
clicking Add MCR.
2 Next, add others files useful for end users. The readme.txt file contains
important information about others files useful for end users. To package additional files or folders, click Add file/directories, select the file or folder you want to package, and click Open.
3 In the Deployment Tool, click the Packaging button ( ).
4 On Windows, t
other than W
distrib fol
indows, it is a
der contains the files you specified.
Note When t
VCREDSIT_
of Microso applicat
X86
ft Visual C++ libraries necessary for running Visual C++
ions.
Copy the Package You Created (Optional)
Copy the of your
package that you created from the
choice or send them to the C/C++ programmer, if applicable.
Using the Command Line (mcc)
You ca run
Usin
Depl
Desired Result Command
n use the command line to execute the Deployment Tool GUI as well
c
command.
mc
g the Deployment Tool from the Command Line. Start the
oyment Tool from the command line by using one of the following options.
he package is a self-extracting executable. On platforms
.zip file. Verify that the contents of the
he self-extracting executable is uncompressed on a system,
is installed. VCREDSIT_X86 installs run-time components
distrib folder to the local folde r
Starts Deployment Tool GUI with the New/Open dialog active
1-16
deploytool (default)
or
deploytool -n
Desired Result Command
Starts Deployment
deploytool project_name.prj
Tool GUI and loads
project_name
Starts Deployment
deploytool -build project_name.prj
Tool command line interface and build s
project_name after
initializing
Starts Deployment
deploytool -package project_name.prj
Tool command line interface and packages
project_name after
initializing
Displays M ATLAB Help for the
deploytool
deploytool -?
command
Deploying with the Magic Square Example
Note TheDeploymentToolcommandlineinterface(CLI)canberunfrom the MATLAB command line window, the Windows command line, or a UNIX shell.
Building Stan da lone Applications and Shared Libr ar ie s Using the Command Line. Instead of the GUI, you can use the
MATLAB Compiler. The following table shows sample commands to create a standalone application or a shared library using prompt.
Desired Result Command
Standalone application from the MATLAB file
mymfunction
mcc -m mymfunction.m
Creates a standalone application named mymfunction.exe on Windows platforms and Windows.
®
mcc command to run
mcc at the operating system
mymfunction on platforms that are not
1-17
1 Getting Started
Desired Result Command
C shared library from the MATLA B files
file1.m, file2.m,and file3.m
C++ shared library from the MATLAB files
file1.m, file2.m,and file3.m
TheMATLABCompilerBuildProcess
To generate and package an application, the use r:
1 Writes an application o r component in MATLAB
2 Invokes the MATLAB Compiler, which:
mcc -B csharedlib:libfiles file1.m file2.m file3.m
Creates a shared library named libfiles.dll on Windows,
libfiles.so on Linux, and libfiles.dylib on Mac OS
mcc -B cpplib:libfiles file1.m file2.m file3.m
®
X.
Creates a shared library named libfiles.dll on Windows,
libfiles.so on Linux, and libfiles.dylib on Mac OS X.
a Examines the input MATLAB files and the external dependency
database to determine the complete list of all functions used by the application or component. As part of this p rocess, MATLAB Compiler determines which files are not able to be compiled and automatically excludes them.
b Determines which functions ar e to be made publicly visible (for example,
those that can be called from another product or environment).
1-18
c Generates the appropriate interface code files based on the public
function list and the complete function list from the preceding steps. The interface code g enerated is also dependent on what target the user wants to create (for example, a Java component, a standalone executable, or a Microsoft Excel add-in).
d Packages compilable functions into a CTF archive, creating a file on the
user’s disk. This archive is embedded by default in the binary executable.
e Optionally, invokes target specific compiler to generate a binary
application or component from the files in C and the interface code libraries provided by The MathWorks.
3 Locates the install package for the MATLAB Compiler Runtime (MCR).
Deploying with the Magic Square Example
4 Collects together the binary, the C TF archive, and the MCR installer (along
with other optional, user-specified files) for the user.
The deployment GUI (
deploytool) automates many o f the steps in the
process for user convenience.
1-19
1 Getting Started
1-20
Deploying with the Magic Square Example
Magic Square Exa
The C or C++ progr
Key Tasks for th
Task
Ensure that you have the needed files from the MATLAB Programmer before proceeding.
Distribute the files. “Distribute to End Users” on page
Install the MCR on target computers by running the MCR Installer. Update system paths on UNIX systems.
Ensure that the final standalone application or library executes reliably in the end-user environment.
ammer performs these tasks.
eCorC++Programmer
mple: C/C++ Programmer Tasks
Reference
“Gathering Files Necessary for Deployment” on page 1-21
1-21
“Install the MCR on Target Computers Without MATLAB and Update System Paths” on page 1-22
“Build an d Test” on page 1-23
Gathering Files Necessary for Deployment
Before by the on pag the fo
beginning, verify that you have access to the following files, packaged
MATLAB Programmer in “Copy the Package You Created (Optional)”
e1-16. EnduserswhodonothaveacopyofMATLABinstalledneed
llowing:
MCR I
comm
read
See mor
nstaller. For locations of all MCR Installers, run the
and.
me.txt
“Packaging Your Deployment Application (Optional)” on page 1-15 for
e information about these files.
file
mcrinstaller
Distribute to End Users
the MATLAB programmer packages the standalone or library (see
If
ackaging Your Deployment Application (Optional)” on page 1-15), paste the
“P
1-21
1 Getting Started
package in a folder on the target machine, and run it. If you are using an archive file, extract the contents to the target machine.
Note If you are using a non-Windows operating system, “console applications” are refe rred to as “standalon e applications”.
Install the MCR on Target Computers Without MATLAB and Update System Paths
On target computers without MATLAB, install the M CR, if it is not already present on the development machine
What is the MCR and Where Do I Get It?
The MATLAB Compiler Runtime (MCR) is an execution engine made up of the same shared libraries MATLAB uses to enable the execution of MATLAB files on systems without an installed version of MA TLAB . In order to deploy a component, you package the MCR along with it. Before you utilize the MCR on a system without MATLAB, run the MCR installer.
1-22
You hav e the option to include the MCR with every package generated by the Deployment Tool. On the Package tab of the Add MCR.
To install the MCR, perform the following tasks on the target machines:
1 If you added the MCR during packaging, open the package to locate the
installer. Otherwise, run the command locations where you can download it.
2 If you are running on a platform other than Windows, set the system paths
on the target machine. Windows paths are set automatically. On Linux and Mac, you can use the run script to set paths.
Setting the paths enables your application to find the MCR.
After you install the MCR, see these resources for more information on working with the various
MWArray APIs:
deploytool interface, click
mcrinstaller to display the
Deploying with the Magic Square Example
For information on the C++ API, see Appendix D, “C++ Utility Library
Reference” in the MATLAB
For information on the
®
Compiler™ User’s Guide on page 1.
MWArray class library (the .NET API), see the
MATLAB Builder NE “Documentation Set” at The MathWorks Web site.
For information on
MWArray types (the Java API), see the MAT LAB Builder
JA “Documentation Set” at The MathWorks Web site.
FormoreabouttheMCR,see“WorkingwiththeMCR”onpage5-18inthe MATLAB
®
Compiler™ User’s Guide on page 1.
Build and Test
Build and test the standalone application or shared library as you would any application in your environment. After you create and distribute the initial application, you continue to enhance it.
Running a 64-Bit Mac Application
Before you run a 64-bit Macintosh®application, you need to use the the Macintosh Application Launcher. See “Running Your 64-Bit M ac Application” on page B-7 in the MATLAB Compiler User Guide for more information.
See Appendix B, “Using MATLAB Compiler User Guide for complete information about building, deploying, and testing UNIX applications with MATLAB Compiler.
®
Compiler on UNIX” in the MATLAB
1-23
1 Getting Started

For More Information

About This Look Here
Detailed information on standalone applications
Creating libraries Chapter 8, “Libraries”
Using the mcc command
Troubleshooting
Chapter 7, “Standalone Applications”
Chapter 6, “Compiler Commands”
Chapter 9, “Troubleshooting”
1-24

Installation and Configuration

“Before You Install MATLAB®Compiler” on page 2-2
®
“Installing MATLAB
“Configuring Your O ptions File with mbuil d” on page 2-6
“If You Have Installation Problems” on page 2-12
Compiler” on page 2-5
2
2 Installation and Configuration

Before You Install MATLAB Compiler

In this section...
“Install MATLAB” on page 2-2
“Install an ANSI C or C++ Compiler” on page 2-2

Install MATLAB

To install M ATLA B, refer to the MATLAB Installation Roadmap in the “Documentation Set”.
See MATLAB Compiler Platform & Requirements for details. The memory and disk requirements to run MATLAB Compiler software are the same as the requirements for MATLAB.

Install an ANSI C or C++ Compiler

Install supported ANSI®C or C++ compiler on your system. Certain output targets require particular compilers.
2-2
To install your ANSI C or C++ compiler, follow vendor instructions that accompany your C or C++ compiler.
Note If you e ncounter problems relating to the installation or use of your ANSI C or C++ compiler, consult your C or C++ compiler vendor.
Supported ANSI C and C++ Windows Compilers
Use one of the following 32-bit C/C++ compilers that create 32-bit Windows dynamically linked libraries (DLLs) or Windows applications:
lcc C version 2.4.1 (included with MATLAB). lcc is a C-only compiler;
it does not compile code with C++.
Microsoft
®
Visual C++®(MSVC).
Before You Install MATLAB®Compiler™
- The only compiler that supports the building of COM objects and Excel
plug-ins is Microsoft Visual C++.
- The only compiler that supports the building of .NET objects is
Microsoft
See the “Product Overview” in the MATLAB Builder NE documentation for a list of supported .NET Framework versions.
Note For an up-to-date list of all the compilers supported by MATLAB and MATLAB Compiler, see the MathWorks™ Technical Support notes at:
http://www.mathworks.com/support/compilers/current_release/
Supported ANSI C and C++ UNIX Compilers
MATLAB Compiler software supports the native system compilers on:
Linux
Linux x86-64
Mac OS X
®
Visual C# Compiler for the Microsoft .NET Framework.
®
MATLAB Compiler software supports
gcc and g++.
Common Installation Issues and Parameters
When you install your C or C++ compiler, you sometimes enco u nte r requests for additional parameters. The following tables provide information about common issues occurring on Windows and UNIX systems where you sometimes need additional input or consideration.
2-3
2 Installation and Configuration

Windows Operating System

Issue Comment
Installation options
Installing debugger files For the purposes of MATLAB
Microsoft Foundation Classes (MFC)
16-bit DLLs Not needed.
ActiveX
Running from the command line
Updating the registry
Installing Microsoft Visual C++ Version 6.0

UNIX Operating System

®
(Recommended) Full installation.
Compiler, it is not necessary to install debugger (DBG) files.
Not needed.
Not needed.
Make sure that you select all relevant options for running your compiler from the command line.
If your installer gives you the option of updating the registry, perform this update.
To change the install location of the compiler, change the location of the
Common folder. Do not change the
location of the default setting.
VC98 folder from its
2-4
Issue Comment
Determine which C or C++ compiler is available on your system.
Determine the path to your C or C++ compiler.
Installing on either Maci or Maci64
See your system administrator.
See your system administrator.
Install X Code from installation DVD.

Installing MATLAB Compiler

In this section...
“Compiler Options” on page 2-5
“On the Windows Operating System” on page 2-5
“On UNIX Operating Systems” on page 2-5

Compiler Options

MATLAB Compiler software requires a supported ANSI C or C++ compiler on your system. Refer to the “Install an ANSI C or C++ Compiler” on page 2-2 for more information.

On the W indows Operating System

To install MATLAB Compiler software on Windows, follow the instructions in the Installation Guide for Windows documentation. If you have a license to install MATLAB Compiler, select the product as you proceed through the installation process.
Installing MATLAB®Compiler™
If MATLAB Compiler does not appear in your list of choices, contact The MathWorkstoobtainanupdatedLicenseFile(
license.dat).

On UNIX Operating Systems

To install MATLAB Compiler on UNIX workstations, follow the instructions in the Installation Guide for UNIX documentation. If you have a license to install MATLAB Compiler, select the product as you proceed through the installation process. If MATLAB Compiler does not appear as one of the installation choices, contact The MathWorks to get an updated license file (
license.dat).
Note To run compiled applications from the DOS command prompt, you must reboot (or log out and log in) after installing MATLAB Compiler.
2-5
2 Installation and Configuration

Configuring Your Options File with mbuild

In this section...
“WhatIsmbuild?”onpage2-6
“When Not to Use mbuild” on page 2-6
“Running mbuild” on page 2-7
“Locating a nd Customizing the Options File” on page 2-9

What Is mbuild?

Running the mbuild configuration script creates an option file that:
Sets the default compiler and linker settings for each supported compiler.
Allows you to changes compilers or compiler settings.
Builds (compiles) your application.
2-6
Note The following mbuild examples apply only to the 32-bit version of MATLAB.
About mbuild and Linking
Static linking is not an option for applications generated by MATLAB Compiler. Compiled applications all must link against library explicitly dynamically loads other shared libraries. You cannot change this behavior on any platform.
MCLMCRRT. This shared

When Not to Use mbuild

Run mbuild before using any deployment product unless you are using one of the following products:
MATLAB Builder JA
MATLAB Builder NE (including the defunct MATLAB COM Builder)
Configuring Your Options File wi th mbuild

Running mbuild

p
1 Run mbuild -setu
2 Select a compiler. Additional platform-specific information follows.
Note The compiler-specific options file specifies that your compiler
contains flags and settings to control the operation of the installed C and C++ compiler. For information on modifying the options file to customize your compiler settings, see “Locating and Customizing the Options File” on page 2-9.
Windows
Executing mbuild -setup on Windows displays t he following message:
Please choose your compiler for building standalone MATLAB applications:
from MATLAB.
Would you like mbuild to locate installed compilers [y]/n? n
Select a compiler: [1] Lcc-win32 C 2.4.1 [2] Microsoft Visual C++ 6.0 [3] Microsoft Visual C++ 2005 SP1 [4] Microsoft Visual C++ 2008 [5] Microsoft Visual C++ 2008 Express
[0] None
The preconfigured options files included with MATLAB for Windows appear in the following table.
Note These options apply only to the 32-bit version of MATLAB.
2-7
2 Installation and Configuration
Options File Compiler
lcccompp.bat
msvc60compp.bat msvc80compp.bat
msvc90compp.bat
UNIX
Executing the command on UNIX displays the following instructions:
C, Version 2.4.1 (included with MATL AB)
Lcc
Microsoft Visual C/C++, Version 6.0 Microsoft Visual C/C++, Version 8.0 Microsoft Visual C/C++, Version 8.0 Express Edition Microsoft Visual C/C++, Version 9.0 Microsoft Visual C/C++, Version 9.0 Express Edition
mbuild -setup
Using the 'mbuild -setup' command selects an options file that is placed in ~/.matlab/
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/
current_release.
current_release and
2-8
Options files control which compiler to use, the compiler and link command options, and the run time 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: matlabroot/bin/mbuildopts.sh : Build and link with MATLAB C-API or MATLAB Compiler-generated library via the system ANSI C/C++ compiler
matlabroot/bin/mbuildopts.sh is being copied to /home/user/.matlab/
current_release/mbuildopts.sh
Configuring Your Options File wi th mbuild
The preconfigured options file for UNIX is mbuildopts.sh,whichusesgcc for Linux and Macintosh.
See the reference page for more information about
mbuild usage, see “Compiling the Driver Application” on page 8-19.
mbuild. For examples of

Locating and Customizing the Options File

“Locating the Options File” on page 2-9
“Changing the Options File” on page 2-10
Locating the Options File
Windows Operating System. To locate your options file on Windows, the
mbuild script searches the following lo cati on s:
Current folder
The
mbuild uses the first occurrence of the op tions file it finds. If it finds no
options file, uses th e factory default options file for that compiler. If compilers, it prompts you to select one.
The Windows such as desktop appearance, recently used files, and Start menu items. The in a subfolder of your
Data\MathWorks\MATLAB\current_release
user profile folder
mbuild searches your machine for a supported C compiler and
mbuild finds multiple
user profile folder contains user-specific information
mbuild utility stores its options files, compopts.bat,
user profile folder, named Application
.
Under Windows with user profiles enabled, your
%windir%\Profiles\username. Howev er, with user profiles disabled, your user profile folder is %windir%. You can determine if user profiles are
user profile folder is
enabled by using the Passwords control panel.
UNIX Operating System. To locate your options file on UNIX, the
mbuild
script searches the following locations:
2-9
2 Installation and Configuration
Current folder
matlabroot/bin
$HOME/.matlab/current_release
mbuild
uses the first occurrence of the options file it finds. If mbuild finds no
options file, an errors message appears.
Changing the Options File
Although it is common to use one options file for all of your MATLAB Compiler related work, you can change your options file at anytime. The resets your default compiler to use the new compiler every time. To reset your C or C++ compiler for future sessions, enter:
mbuild -setup
Modifying the Options File on Windows. You can use the -setup option to change your options file settings on Windows. The appropriate options file to your
user profile folder.
-setup option copies the
To modify y ou r options file on Windows:
1 Enter mbuild -setup to make a copy of the appropriate options file in
your local area.
2 Edit your copy of the options file in your user profile folder to correspond
to your specific needs, and save the modified file.
After completing this process, the
mbuild script uses the new options file
every time with your modified settings.
setup option
2-10
Modifying the Options File on UNIX. You can use the
setup option to
change your options file settings on UNIX. For example, to change the current linker settings, use the
The
setup option creates a user-specific matlab folder in your home folder
setup option.
and copies the appropriate options file to the folder.
Do not confuse these user-specific
matlab folders with the system matlab
folder.
Configuring Your Options File wi th mbuild
To modify your options file on the UNIX:
1 Use mbuild -setup to make a copy of the appropriate options file in your
local area.
2 Edit your copy of the options file to correspond to your specific needs, and
save the modified file.
2-11
2 Installation and Configuration

If You Have Installation Problems

You can contact The MathWorks:
ViatheWebat
click My Account to access your MathWorks Account, and follow the instructions.
Via e-mail at
www.mathworks.com. On the MathWorks home page,
service@mathworks.com.
2-12

Writing Deployable MATLAB Code

“The MATLAB Application Deployment Products” on page 3-2
“Building Your Application with the Application Deployment Products and
the Deployment Tool” on page 3-4
“Guidelines for Writing Deployable M ATLA B Code” on page 3-10
“Working with MATLAB Data Files Using Load and Save” on page 3-14
3
3 Writing Deployable MATLAB
®
Code

The MATLAB Application Deployment Products

The MATLAB S
Product
MATLAB Compiler
MATLAB Builder NE
MATLAB Builder JA
MATLAB expert
No IT experience
MATLAB
Programmer
The followin
No access to IT systems
g tables summarizes the target applications supported by each
product.:
uite of Applic ation Deployment Products
Target
CandC++
Create Standalone Executables?
Create Function Libraries?
YesYesYesNo standalones and libraries
C# .NET
No Yes Yes Yes components Visual Basic COM components
Java
No Yes Yes Yes components
Develops model
Uses the builder tools to create a component that is given to the business service developer
Create Applications
Create Web
Applications? with Graphics?
3-2
MATLAB Builder EX
Microsoft Excel add-ins
No Yes Yes No
The MATLAB®Application Deployment Products
The MATLAB®Application Deployment Products
Each of the builder products uses the MATLAB Compiler core code to create deployable components.
3-3
3 Writing Deployable MATLAB
®
Code
Building Your Application with the Application Deployment Products and the
In this section...
“What Is the Difference Between the Deployment Tool and the mcc Command Line?” on page 3-4
“How Does MATLAB®Compiler Software Build My Application?” on page 3-4
“What You Should Know About the Dependency Analysis Function (depfun)” on page 3-5
“Compiling MEX-Files, DLLs, or Shared Libraries” on page 3-6
“The Role of the Component Technology File (CTF Archive)” on page 3-7
Deployment Tool
What Is th and the m
Using th would i Deploy custom the sa
Using
Perf
Main
Pac
Ho Ap
MA
nvoke using the MATLAB Compiler
ment Tool interactive menus and dialogs build
ized to your specification. As such, your MATLAB code is processe d
me way as if you were compiling it using
the Deployment Tool, you:
orm related deployment tasks with a single intuitive GUI.
tain related information in a convenient project file. Your project
e persists between sessions. Your previous project loads automatically
stat
n the Deployment Tool starts. You load previously stored compiler
whe
jects from a prepopulated menu.
pro
kage applications for distribution.
w Does MATLAB Compiler Software Build My plication?
TLAB Compiler software:
e Difference Between the Deployment Tool cc Command Line?
e D eploym ent Tool (
deploytool) GUI, you perform any function you
mcc command-line interface. The
mcc commands that are
mcc.
3-4
Building Your Application with the Application Deployment Products and the Deployment Tool
1 Parses command-line arguments and classifies by type the files you provide.
2 Analyzes files for dependencies using the Dependency Analysis Function
(
depfun). Dependencies affect deployability and originate from file
contents—functions called by the file. Deployability is affected by:
File type — MATLAB, Java, MEX, and so on.
File location — MATLAB, MATLAB toolbox, user code, and so on.
File deployability — Whether the file is deployable outside of MATLAB
For more information about
depfun, see “What You Should Know About
the D ependency Analysis Function (depfun)” on page 3-5.
3 Validates MEX-files. In particular, mexFunction entry points are verified).
For more details about MEX-file processing, see “Compiling MEX-Files, DLLs, or Shared Libraries” on page 3-6.
4 Creates a CTF archive from the input files and their dependencies.
For more details about CTF archives see “The Role of the Component Technology File (CTF Archive)” on page 3-7.
5 Generates target-specific wrapper code. For example, the wrapper for a C
main function is very different than the wrapper for a Java interface class.
6 Invokes a third-party target-specif ic compiler to create the appropriate
binary software com ponent (a standalone executable, a Java JAR file, and so on).
For details about how MATLAB Compiler software builds your deployable component, see “The MATLAB
®
Compiler Build Process” on page 1-18.
What You Should Know About the Dependency Analysis Function (depfun)
MATLAB Compiler uses a dependency analysis function (depfun)to determine the list of necessary files to include in the CT F package. In some cases, this process includes an large number of files. This is often true when MATLAB object classes exist in the compilation and overloaded methods at compile time. Dependency analysis also processes
include/exclude filesoneachpass(seethemcc flag “-a Add to Archive” on
page 13-23).
depfun cannot resolve
3-5
3 Writing Deployable MATLAB
Tip To improve compile time performance and lessen application size, prune
the path with “-N Clear Path” on page 13-29, “-p Add Directory to Path” on page 13-30, or by specifying Toolboxes on Path in the
depfun searches for executable content such as:
MATLAB files
P-files
®
Code
deploytool Settings
Java classes and
.fig files
.jar files
MEX-files
depfun does not search for data files of any kind (except MAT files). You
must manually
include data files.

Compiling MEX-Files, DLLs, or Shared Libraries

When you compile MATLAB functions containing MEX-files, ensure that
depfun can find them—doing so allows you to avoid many common
compilation problems. In particular, note that:
depfun cannot examine MEX-files, DLLs, or shared libraries to determine
their dependencies. Explicitly include all binaries these files require either with the Deployment Tool unde r Settings.
If you have any doubts that
a MEX-file, DLL, or shared library—manually include it. Do this with either the the Deployment Tool under Settings.
Not all functions are compatible with MATLAB Compiler. Check the file
mccExcludedFiles.log after your build completes. This file lists all
functions called from your application that you cannot deploy.
mcc -a option or the options on the Advanced tab in the
depfun can find a MATLAB function called by
mcc -a option or by using the options on the Advanced tab in
3-6
Building Your Application with the Application Deployment Products and the Deployment Tool

TheRoleoftheComponentTechnologyFile(CTF Archive)

Each application or shared library produced by MATLAB Compiler has an associated Component Technology File (CTF) archive. The archive contains all the MATLAB based content (MATLAB files, MEX-files, and so on) associated with the compo ne nt.
MATLAB Compiler also embeds a CTF) archive in each generated binary. The CTF houses all deployable files. All MATLAB files encrypt in the CTF archive using the Advanced Encryption Standard (AES) cryptosystem .
If you choose the extract the CTF archive as a separate file the files remain encrypted. For more information on how to extract the CTF archive refer to the references in the following table.
Information on CTF Archive Embedding/Extraction and Component Cache
Product
MATLAB Compiler “Overriding Default CTF Archive
MATLAB Builder NE “Overriding Default CTF Archive
MATLAB Builder JA “Using M CR Component Cache and
MATLAB Builder EX “Overriding Default CTF Archive
Refer to
Embedding Using the MCR Component Cache” on page 6-20
Embedding for Components Using the MCR Component Cache”
MWComponentOptions”
Embedding for Components Using the MCR Component Cache”
3-7
3 Writing Deployable MATLAB
®
Code
3-8
Building Your Application with the Application Deployment Products and the Deployment Tool
Additional Details
Multiple CTF archives, such as those generated with COM, .NET, or Excel components, can coexist in the same user application. You cannot, however, mix and match the MATLAB files they contain. You cannot combine encrypted and compressed MATLAB files from multiple CTF archives into another CTF archive and distribute them.
All the M ATLA B files from a given CTF archive associate with a unique cryptographic key. MATLAB files with different keys, placed in the same CTF archive, do not execute. If you want to generate another application with a different mix of MATLAB files, recompile these MATLAB files into a new CTF archive.
MATLAB Compiler deleted the CTF archive and generated binary following a failed compilation, but only if these files did not exist before compilation initiates. Run
Caution Release Engineers and Software Configuration Managers: Do not use build procedures or processes that strip shared libraries on CTF archives. If you do, you can possibly strip the CTF archive from the binary, resulting in run-time errors for the driver application.
help mcc -K for more information.
3-9
3 Writing Deployable MATLAB
®
Code

Guidelines for Writing Deployable MATLAB Code

In this section...
“Compiled Applications Do Not Process MATLAB Files at Runtime” on page 3-10
“Do Not Rely on Changing Directory or Path to Control the Execution of MATLAB Files” on page 3-11
“Use ismcc and isdeployed Functions To Execute Deployment-Specific Code Paths” on page 3-11
“Gradually Refactor Applications That Depend on Noncom pilable Functions” on page 3-12
“Do Not Create or Use Nonconstant Static State Variables” on page 3-12

Compiled Applications Do Not Process MATLAB Files at Runtime

The MATLAB Compiler was designed so that you can deploy locked down functionality. Deployable MATLAB files are suspended or frozen at the time MATLAB Compiler encrypts them—they do not change from that point onward. This does not mean that you cannot deploy a flexible application—it means that you must design your application with flexibility in mind.Ifyou want the end user to be able to choose between two different methods, for example, they both must be compiled in.
3-10
The MCR only works on MATLAB code that was encrypted when the component was built. Any function or process that dynamically generates new MATLAB code will not work against the MCR.
Some MATLAB toolboxes, such as the Neural Network Toolbox™ product, generate MATLAB code dynamically. Because the MCR only executes encrypted MATLAB files, and the Neural Network Toolbox generates unencrypted MATLAB files, some functions in the Neural Network Toolbox cannot be deployed.
Similarly, functions that need to examine the contents of a MATLAB function file cannot be deployed.
HELP, for example, is dynamic and not available in
Guidelines for Writing Deployable MATLAB®Code
deployed mode. You can use LOADLIBRARY in deployed mode if you provide it with a MATLAB function prototype.
Instead of compiling the function that generates the MATLAB code and attempting to deploy it, perform the following tasks:
1 Run the code once in MATLAB to obtain your generated function.
2 Compile the MATLAB code with MATLAB Compiler, including the
generated function.
Tip Another alternative to using EVAL or FEVAL is using anonymous function handles.
If you require the ability to create MATLAB code for dynamic runtime processing, your end-users must have an installed copy of MATLA B.
Do Not Rely on Changing Director y or Path to Control the Execution of MATLAB Files
In general, good programming practices advise against redirecting a program search path dynamically within the code. Many programmers are prone to this behavior since it mimics the actions they usually perform on the command line. However, this can lead to problems when deploying code.
For example, in a deployed application, the MATLAB and Java paths are fixed and cannot change. Therefore, any attempts to change these paths (using the
If you find you cannot avoid placing
ismcc and isdeployed. See the next section for details.
cd command or the addpath command) fails
addpath calls in your MATLAB code, use
Use ismcc and isdeployed Functions To Execute Deployment-Specific Code Paths
The isdeployed function allows you to specify which portion of your MATLAB code is deployable, and which is not. Such specification minimizes your compilation errors and helps create m ore efficient, maintainable code.
3-11
3 Writing Deployable MATLAB
For example, you find it unavoidable to use addpath when writing your
startup.m.Usingismcc and isdeployed, you specify when and what is
compiled and executed.
®
Code
For a n example of using Standalone Application” on pa ge 6-31.
isdeployed, see “Passing Arguments to and from a
Gradually Refactor Applications That Depend on Noncompilable Functions
Over time, refactor, streamline, and modul ari ze MATLAB code containing non-compilable or non-deployable functions that use Your eventual goal is “graceful degradation” of no n-deploya ble code. In other words, the code must present the end user with as few obstacles to deployment as possible until it is practically eliminated.
Partition your code into design-time and run-time code sections:
Design-time code is code that is currently evolving. Almost all code goes
through a phase of perpetual rewriting, debugging, and optimization. In some toolboxes, such as the Neural Network Toolbox product, the code goes through a period of self-training as it reacts to various data permutations and patterns. Such code is almost never designed to be deployed.
Run-time code, on the other hand, has solidified or become stable—it is in a
finishedstateandisreadytobedeployedbytheenduser.
Consider creating a separate directory for code that is not meant to be deployed or for code that calls undeployable code.
ismcc and isdeployed.
3-12

Do Not Create or Use Nonconstant Static State Variables

Avoid using the following:
Global variables in MATLAB code
Static variables in MEX-files
Static variables in Java code
Guidelines for Writing Deployable MATLAB®Code
The state of these variables is persistent and shared with everything in the process.
Persistent variables can cause problems because the MCR process runs in a single thread. You cannot load more than one of these non-constant, static variables into the same process. In addition, these static variables do not work well in multithrea ded applications.
If you must u se static variables, bind them to instances. For example, defining instance variables in a Java class is preferable to defining the variable as
static.
Note This guideline does not apply to MATLAB Builder EX customers. When programming with Microsoft Excel, you can assign global variables to large matrices that persist between calls.
3-13
3 Writing Deployable MATLAB
®
Code

Working with MATLAB Data Files Using Load and Save

If you r deployed application uses MATLAB data files (MAT-files), it is helpful to code processing.
LOAD and SAVE functions to manipulate the data and store it for later
Use
Specify the data file by full path name or relative to
All MAT-files are unchanged after
For more information about C TF archives, see “The Role of the Component Technology File (CTF Archive)” on page 3-7.
Use the following example as a template for manipulating your MATLAB data inside, and outside, of MATLAB.
isdeployed to determine if your code is running in or out of the
MATLAB workspace.
ctfroot.
mcc runs. These files are not encrypted
when written to the CTF archive.
Using Load/Save Functions to Process MATLAB Data for Deployed Applications
The following example specifies three MATLAB data files:
user_data.mat
userdata/extra_data.mat
../externdata/extern_data.mat
Compile ex_loadsave.m with the following mcc command:
3-14
mcc -mvC ex_loadsave.m -a 'user_data.mat' -a
'./userdata/extra_data.mat' -a '../externdata/extern_data.mat'
loadsave.m
ex_
function ex_loadsave
Working with MATLAB Data Files Using Load and Save
% This example shows how to work with the
% "load/save" functions on data files in
% deployed mode. There are three source data files
% in this example.
% user_data.mat
% userdata/extra_data.mat
% ../externdata/extern_data.mat
%
% Compile this example with the mcc command:
% mcc -mC ex_loadsave.m -a 'user_data.mat' -a
% './userdata/extra_data.mat'
% -a '../externdata/extern_data.mat'
% All the folders under the current main MATLAB file directory will
% be included as
% relative path to ctfroot; All other folders will have the
% folder
% structure included in the ctf archive file from root of the
% disk drive.
%
% If a data file is outside of the main MATLAB file path,
% the absolute path will be
% included in ctf and extracted under ctfroot. For example:
% Data file
% "c:\$matlabroot\examples\externdata\extern_data.mat"
% will be added into ctf and extracted to
% "$ctfroot\$matlabroot\examples\externdata\extern_data.mat".
%
% All mat/data files are unchanged after mcc runs. There is
% no excryption on these user included data files. They are
% included in the ctf archive.
%
% The target data file is:
% ./output/saved_data.mat
% When writing the file to local disk, do not save any files
% under ctfroot since it may be refreshed and deleted
% when the application isnext started.
%==== load data file =============================
if isdeployed
% In deployed mode, all file under CTFRoot in the path are loaded
3-15
3 Writing Deployable MATLAB
®
Code
% by full path name or relative to $ctfroot.
% LOADFILENAME1=which(fullfile(ctfroot,mfilename,'user_data.mat'));
% LOADFILENAME2=which(fullfile(ctfroot,'userdata','extra_data.mat'));
LOADFILENAME1=which(fullfile('user_data.mat'));
LOADFILENAME2=which(fullfile('extra_data.mat'));
% For external data file, full path will be added into ctf;
% you don't need specify the full path to find the file.
LOADFILENAME3=which(fullfile('extern_data.mat'));
else
%running the code in MATLAB
LOADFILENAME1=fullfile(matlabroot,'extern','examples','compiler',
'Data_Handling','user_data.mat');
LOADFILENAME2=fullfile(matlabroot,'extern','examples','compiler',
'Data_Handling','userdata','extra_data.mat');
LOADFILENAME3=fullfile(matlabroot,'extern','examples','compiler',
'externdata','extern_data.mat');
end
% Load the data file from current working directory
disp(['Load A from : ',LOADFILENAME1]);
load(LOADFILENAME1,'data1');
disp('A= ');
disp(data1);
3-16
% Load the data file from sub directory
disp(['Load B from : ',LOADFILENAME2]);
load(LOADFILENAME2,'data2');
disp('B= ');
disp(data2);
% Load extern data outside of current working directory
disp(['Load extern data from : ',LOADFILENAME3]);
load(LOADFILENAME3);
disp('ext_data= ');
disp(ext_data);
%==== multiple the data matrix by 2 ==============
result = data1*data2;
disp('A*B=');
disp(result);
Working with MATLAB Data Files Using Load and Save
%==== save the new data to a new file ===========
SAVEPATH=strcat(pwd,filesep,'output');
if ( ~isdir(SAVEPATH))
mkdir(SAVEPATH);
end
SAVEFILENAME=strcat(SAVEPATH,filesep,'saved_data.mat');
disp(['Save the A*Bresult to : ',SAVEFILENAME]);
save(SAVEFILENAME, 'result');
3-17
3 Writing Deployable MATLAB
®
Code
3-18

Compilation Tasks

“Input and Output Files” on page 4-2
“Dependency Analysis F unction (depfun) and User Interaction with the
Compilation Path” on page 4-8
4
4 Compilation Tasks

Input and Output Files

In this section...
“Standalone Executable” on page 4-2
“C Shared Library” on page 4-3
“C++ Shared Library” on p age 4-5
“Macintosh 64 (Maci64)” on page 4-7

Standalone Executable

In this example, MATLAB Compiler takes the MATLAB files foo.m and
bar.m as input and generates a standalone called foo.
mcc -m foo.m bar.m
File Description
foo_main.c
foo_mcc_component_data.c
foo
run_component.sh
The main-wrapper C source file containing the program’s
main function. T he main function takes the input
arguments that are passed on the command line and passesthemasstringstothe
C source file containing data needed by the MCR to run the application. This data includes path information, encryption keys , and other initialization information for the MCR.
The main file of the application. This file reads a nd executes the content stored in the embedded CTF archive. On Windows, this file is
mcc
(including Mac) system s for standalone app l ications. It temporarily sets up the environment variables needed at runtime and executes the application. On Windows,
mcc doesn’t generate this run script file, because the
environment variables have already been set up by the installer. In this case, you just run your standalone
.exe file.
foo function.
foo.exe.
generates run_<component>.sh file on UNIX
4-2

CSharedLibrary

In this example,
bar.m as input an
mcc -W lib:libfoo -T link:lib foo.m bar.m
File Description
libfoo.c
libfoo.h
libfoo_mcc_component_data.c
libfoo.exports
libfoo
MATLAB Compiler takes the MATLAB files
d generates a C shared library called
The library wrapper C source file containing the exported functions of the library representingtheCinterfacetothetwo MATLAB functions ( as library initialization code.
The library wrapper header fi le. T his file is included by applications that call the exported functions of
C source file containing data needed by the MCR to initialize and use the library. This data includes path information, encryption keys, and other initialization for the MCR.
The exports file used by mbuild to link the library.
The shared library binary file. O n Windows, this file is
libfoo.dll.
Input and Output Files
foo.m and
libfoo.
foo.m and bar.m)aswell
libfoo.
Note UNIX extensions vary depending on the platform. See the External Interfaces documentation for additional information.
4-3
4 Compilation Tasks
File Description
libname.exp
libname.lib
Exports file used by the linker. The linker uses theexportfiletobuildaprogramthatcontains exports, usually a dynamic-link library (. The import library is used to resolve references to those exports in other programs.
Import library. An import library is used to validate that a certain identifier is legal, and will be present in the program when the . loaded. The linker uses the information from the import library to build the lookup table for using identifiers that are not included i n the .
dll.Whenanapplicationor.dll is l inked, an
import library may be generated, which will be used for all future . symbols in the application or .
dll).
dll is
dlls that depend on the
dll.
4-4
Input and Output Files
C++ Shared Libra
In this example,
bar.m as input an
mcc -W cpplib:libfoo -T link:lib foo.m bar.m
MATLAB Compiler takes the MATLAB files
d generates a C++ shared library called
ry
File Description
libfoo.cpp
The library wrapper C++ source file containing the exported functions of the library representing theC++interfacetothetwoMATLABfunctions (
foo.m and bar.m) as well as library initialization
code.
libfoo.h
The library wrapper header file. This file is included by applications that call the exported functions of
libfoo_mcc_component_data.c
C++ source file containing data needed by the MCR to initial ize and use the library. This data includes path in formation, encryption keys, and other initialization for the MCR.
libfoo.exports
libfoo
The exports file used by mbuild to link the library.
The shared library binary file. On Windows, this file is
libfoo.dll.
foo.m and
libfoo.
libfoo.
Note UNIX extensions vary depending on the platform. See the External Interfaces documentation for additional information.
4-5
4 Compilation Tasks
File Description
libname.exp
libname.lib
Exports file used by the linker. The linker uses theexportfiletobuildaprogramthatcontains exports (usually a dynamic-link library (. The import library is used to resolve references to those exports in other programs.
Import library. An import library is used to validate that a certain identifier is legal, and will be present in the program when the . loaded. T he linker uses the information from the import library to build the lookup table for using identifiers that are not included in the . an ap p lication or . may be generated, which will need to be used for all future . application or .
dll).
dll is
dll.When
dll is linked, an import library
dlls that depend on the symbols in the
dll.
4-6
Input and Output Files
Macintosh 64 (Ma
For 64-bit Macin
File Description
foo.app
foo
run_component.sh
tosh, a Macintosh application bundle is created.
ci64)
The bundle created for executable foo. Execution of the bundle occurs through
foo.app/Contents/MacOS/foo.
Application
The generated shell script which executes the application through the bundle.
4-7
4 Compilation Tasks
Dependency Analysis Function (depfun) and User Interaction w ith the Compilation Path

addpath and rmpath in MATLAB

If you run MATLAB Compiler from the MATLAB prompt, you can use the
addpath and rmpath commands to modify the MATLAB path before doing a
compilation. There are two disadvantages:
The path is modified for the current MATLAB session o nly.
If MATLAB Compiler is run outside of MATLAB, this doesn’t work unless a
savepath is done in MATLAB.
Note The path is also modified for any interactive work you are doing in the MATLAB environment as well.
4-8

Passing -I <directory> on the Command Line

You can use the -I option to add a folder to the beginning of the list of paths to use for the current compilation. This feature is useful when you are compiling files that are in folders currently not on the MATLAB path.

Passing -N and -p <directory> on the Command Line

There are two MATLAB Compiler options that provide more detailed manipulation of the path. This feature acts like a “filter” applied to the MATLAB path for a given compilation. The first option is the
mcc command line effectively clears the path of all folders except the
following core folders (this list is subject to change over time):
matlabroot/toolbox/matlab
matlabroot/toolbox/local
matlabroot/toolbox/compiler/deploy
matlabroot/toolbox/compiler
-N. Passing -N on
Dependency Analysis Function (depfun) and User Interaction with the Compilation Path
It also retains all subfolders of the above list that appear on the MATLAB path at compile time. Including
-N on the command line allows you to
replace folders from the original path, while retaining the relative ordering of the included folders. All subfolders of the included folders that appear on the original path are also included. In addition, the
-N option retains
all folders that the user has included on the path that are not under
matlabroot/toolbox.
Use the
-p option to add a folder to the compilation path in an order-sensitive
context, i.e., the same order in which they are found on your MATLAB path. The syntax is
p <directory>
where <directory> is the folder to be included. If <directory> is not an absolute path, it is assumed to be under the current working folder. The rules for how these folders are included are
If a folder is included with
-p that is on the original MATLAB path, the
folder and all its subfolders that appear on the original path are added to the compilation path in an order-sensitive context.
If a folder is included with
that folder is not included in the compilation. (You can use
If a path is added with the
-p that is not on the original MATLAB path,
-I to add it.)
-I option while this feature is active (-N has
been passed) and it is already on the MATLAB path, it is added in the order-sensitive context as if it were included with is added to the head of the path, as it normally would be with
-p. Otherwise, the folder
-I.
Note The -p option requires the -N option on the mcc command line.
4-9
4 Compilation Tasks
4-10

Deployment Process

This chapter tells you how to deploy compiled MATLAB code to programmers and to end users.
“Overview” on page 5-2
“Deploying to Programmers” on page 5-3
“Deploying to End Users” on page 5-9
“Working with the MCR ” on page 5-18
“Deploying a Standalone ApplicationonaNetworkDrive”onpage5-39
®
“MATLAB
“Using MATLAB
page 5-41
Compiler Deployment Messages” on page 5-40
®
Compiler Generated DLLs in Windows Services” on
5
“Reserving Memory for Deployed Applications with MATLAB Memory
Shielding” on page 5-42
5 Deployment Process

Overview

After you create a library, a component, or an application, the next step is typicallytodeployittootherstouseon their machines, independent of the MATLAB environment. These users can be programmers who want to use the library or component to develop an application, or end users who want to run a standalone application.
“Deploying to Programmers” on page 5-3
“Deploying to End Users” on page 5-9
Note When you deploy, y ou provide the wrappers for the compiled MATLAB
code and the software needed to support the wrappers, including the M CR. The M CR is version specific, so you must ensure that programmers as well as users have the proper version of the MCR installed on their machines.
5-2

Deploying to P rogrammers

In this section...
“StepsbytheProgrammertoDeploytoProgrammers”onpage5-3
“What Softw are Does a Programmer Need?” on page 5-4
“Ensuring Memory for Deployed Applications” on page 5-7

Steps by the Programmer to Deploy to Programmers

Note If you are programming on the same machine where you created the
component, you can skip the steps described here.
1 Create a package that contains the software necessary to support the
compiled MATLAB code. It is frequently helpful to install the MCR on development machines, for testing purposes. See “What Software Does a Programmer Need?” on page 5-4
Deploying to Programmers
Note You can use the Deployment Tool to create a package for programmers. For Windows platforms, the package created by the Deployment Tool is a self-extracting executable. F or UNIX platforms, the package created by the Deployment Tool is a zip file that must be decompressed and installed manually. See Chapter 1, “Getting Started” to get started using the Deployment Tool.
2 Write instructions for how to use the package.
a If your package was created with the Deployment Tool, Windows
programmers can just run the self-extracting executable created by the Deployment Tool. UNIX programmers must unzip and install manually.
b All programmers must set path environment variables properly. See
“Directories Required for Development and Testing” on page 11-2.
3 Distribute the package and instructions.
5-3
5 Deployment Process

What Software Does a Programmer Need?

Thesoftwarethatyouprovidetoaprogrammerwhowantstousecompiled MATLAB code depends on which of the following kinds of software the programmer will be using:
“Standalone Application” on page 5-4
“C or C++ Shared Library” on page 5-5
“.NET Component” on page 5-6
“COM Component” on page 5-6
“Java Component” on page 5-7
®
“COM Component to Use with Microsoft
Standalone Application
To distribute a standalone application created with MATLAB Compiler to a development machine, create a package that includes the following files.
Excel” on page 5-7
5-4
Software Module
MCRInstaller.exe
(Windows)
MCRInstaller.bin
(UNIX)
MCRInstaller.dmg
(Mac)
Description
MCRInstaller is a self-extracting executable that
installs the necessary co mponents to develop your application. This file is included with MATLAB Compiler.
MCRInstaller is a self-extracting executable that
installs the necessary co mponents to develop your application on UNIX machines (other than
®
Mac
). This file is included with MATLAB
Compiler.
MCRInstaller.dmg is a self-extracting executable
that installs the necessary components to develop your application on Mac machines. This file is included with MATL A B Compiler.
Deploying to Programmers
Software Module
application_name.exe
(Windows)
application_name
Description
Application created by MATLAB Compiler. Maci64 must include the bundle directory hierarchy.
(UNIX)
application_name.app
(Maci64)
Note If you are using a non-Windows operating system, “console applications” are refe rred to as “standalon e applications”.
C or C++ Shared Library
To distribute a shared library created with MATLAB Compiler to a development machine, create a package that includes the following files.
Software Module Description
MCRInstaller.bin
(UNIX)
MCRInstaller.dmg
(Mac)
MCRInstaller.exe
(Windows)
libmatrix
libmatrix.h
libmatrix.lib
MATLAB Compiler Runtime library archive; platform-dependent file that must correspond to the end user’s platform
MCRInstaller.dmg is a self-extracting executable
that installs the necessary components to develop your application on Mac machines. T his file is included with MATLAB Compiler.
Self-extracting MATLAB Compiler Runtime library utility; platform-dependent file that must correspond to the end user’s platform
Shared library; extension varies by platform, for example,
DLL on Windows
Library header file
Application library file; file is needed to create the driver application for the shared library.
5-5
5 Deployment Process
.NET Component
Todistributea.NETcomponenttoadevelopment machine, create a package that includes the following files.
Software Module
componentName.xml
componentName.pdb (if Debug
option is se lected)
componentName.dll
MCRInstaller.exe
Description
Documentation files
Program Database File, which contains debugging information
Component assembly file
MCR Installer (if not already installed on the target machine)
COM Component
To distribute a COM component to a development machine, create a package that includes the following files.
Software Modu le
mwcomutil.dll
componentname_ version.dll
MCRInstaller.exe
Description
Utilities required for array processing. Provides type definitions used in data conversion.
Component that contains compiled MATLAB code.
Self-extracting M ATL AB Compiler Runtime library utility; platform-dependent file that must correspond to the end user’s platform.
5-6
MCRInstaller.exe installs MATLAB
Compiler Runtime (MCR), which users of your component need to install on the targe t machineonceperrelease.
Deploying to Programmers
Java Component
To distribute a Java component to a development machine, create a package that includes the Java interface to MATLAB code.
Note For more information, see the MWArray Javadoc, which is searchable from the Help or from the MathWorks Web site.
componentname.jar file, a Java package containing the
COM Component to Use with Microsoft Excel
To distribute a COM component for Excel to a development machine, create a package that includes the following files.
Software Module
componentname_projectversion.dll
MCRInstaller.exe
*.xla
Description
Compiled component.
Self-extracting MATLAB Compiler Runtime library utility; platform-dependent file that must correspond to the end user’s platform.
MCRInstaller.exe installs the
MATLAB Compiler Runtime (MCR), which users of your component need to install on the target machine once per release.
Any user-created Excel add-in files found in the
<projectdir>\distrib folder

Ensuring Memor y for Deployed Applications

If you are having trouble obtaining memory for your deployed application, use MATLAB Memory Shielding for deployed applications to ensure a maximum amount of contiguous allocated me m ory. See “Reserving Memory
5-7
5 Deployment Process
for Deployed Applications with MATLAB Memory Shielding” on page 5-42 for more information.
5-8

Deploying to End Users

In this section...
“Steps by the Programmer to Deploy to End Users” on page 5-9
“What Softw are Does the End User Need?” on page 5-12
“Using Relative Paths with Project Files” on page 5-15
“Porting G enerated Code to a Different Platform” on page 5-15
“Extracting a CTF Archive Without Executing the Component” on page 5-16
“Ensuring Memory for Deployed Applications” on page 5-16

Steps by the Programmer to Deploy to End Users

For an end user to run an application or use a library that contains compiled MATLAB code, there are two sets of tasks. Some tasks are for the programmer who developed the application or library, and some tasks are for the end use r.
Deploying to End Users
1 Create a package that contains the software needed at run time. See “What
Software Does a Programmer Ne ed? ” on page 5-4 for more details.
5-9
5 Deployment Process
Note The package for end users must include the .ctf file, which includes
all the files in your preferences folder. Be aware of the following with regards to preferences:
MATLAB preferences set at compile time are inherited by the compiled
application. There fore, include no files in your preferences folder that youdonotwantexposedtoendusers.
Preferences set by a compiled application do not affect the MA TLA B
preferences, and preferences set in MAT LAB do not affect a compiled application until that application is recompiled. MATLAB does not save your preferences folder until you exit MATLAB. Therefore, if you change your MATLAB preferences, stop and restart MATLAB before attempting to recompile using your new p references.
.
The preferences folder is as follows:
5-10
$HOME/.matlab/current_release on UNIX
system root\profiles\user\application data\mathworks\
matlab\current_release
on Windows
The folder will be stored in the CTF archive in a folde r with a generated name, such as:
mwapplication_mcr/myapplication_7CBEDC3E1DB3D462C18914C13CBFA649.
2 Write instructions for the end user. See “Steps by the End User” on page
5-10.
3 Distribute the package to your end user, along with the instructions.

Steps by the End User

1 Open the package containing the software needed at run time.
Deploying to End Users
2 Run MCRInstaller once on the target machine, that is, the machine where
you want to run the application or library. The
MCRInstaller opens a
command window and begins preparation for the installation. See “Using the MCR Installer GUI” on page 5-11.
3 If you are deploying a Java application to end users, they must set the
class path on the target m achine.
Note for Windows®Applications You must have administrative privileges to install the MCR on a target machinesinceitmodifiesboththesystem registry and the system path.
Running the
MCRInstaller after the MCR has been set up on the target
machine requires only user-level privileges.

Using the MCR Installer GUI

1 When the MCR Installer wizard appears, click Next to begin the
installation. Click Next to continue.
2 In the Select Installation Folder dialog box, specify where you want to
install the MCR and whether you want to install the MCR for just yourself or others. Click Next to continue.
Note The Install MATLAB Compiler Runtime for yourself, or for anyone who uses this computer option is not implemented for this release. The current default is Everyone.
3 Confirm your selections by clicking Next.
The installation begins. The process takes some time due to the quantity of files that are installed.
The MCRInstaller automatically:
Copiesthenecessaryfilestothetarget folder you specified.
5-11
5 Deployment Process
Registers the components as needed.
Updates the system path to point to the MCR binary folder, which is
<target_directory>/<version>/runtime/win32|win64.
4 When the installation completes, click Close on the Installation Completed
dialog box to exit.

What Software Does the End User Need?

The software required by end users depends on which of the following kinds of software is to be run by the user:
“Standalone Compiled Application That Accesses Shared Library” on page
5-12
“.NET Application” on page 5-13
“COM Application” on page 5-13
“Java Application” on page 5-14
“Microsoft
®
Excel Add-In” on page 5-14
5-12
Standalone Compiled Application That Accesses Shared Library
To distribute a shared library created with MATLAB Compiler to end users, create a package that includes the following files.
Component Description
MCRInstaller.exe
(Windows)
matrixdriver.exe
(Windows)
matrixdriver
(UNIX)
Self-extracting MATLAB Compiler Runtime library utility; platform -dependent file that must correspond to the end user’s platform.
Application
Component Description
libmatrix
Shared library; extension varies by platform. Extensions are:
Deploying to End Users
Windows —
.dll
Linux, Linux x86-64 — .so
Mac OS X — .dylib
.NET Application
To distribute a .NET application that uses components created with MATLAB Builder NE, create a package that includes the following files.
Software Module
componentName.xml
componentName.pdb
(if Debug option is
Description
Documentation files
Program Database File, which contains debugging information
selected)
componentName.dll
MCRInstaller.exe
Component assembly file
MCR Installer (if not already installed on the target machine)
application.exe
Application
COM Application
To distribute a COM application that uses components created with MATLAB Builder NE or MATLAB Builder EX, create a package that includes the following files.
5-13
5 Deployment Process
Software Module
componentname.ctf
Description
Component Technology File (ctf) archive. This is a platform-dependent file that must correspond to the enduser’splatform.
componentname _version.dll
_install.bat
MCRInstaller.exe
Component that contains compiled MATLAB code
Script run by the self-extracting executable
Self-extracting MATLAB Compiler Runtime library utility; platform-dependent file that must correspond to the end user’s platform.
MCRInstaller.exe installs MATLAB
Compiler Runtime (MCR), which users of your component n eed to install on the target machine once per release.
application.exe
Application
Java Application
To distribute a Java application created with MATLAB Builder JA, create a
componentname.jar file. To deploy the application on computers without
MATLAB, you must include the MCR when creating your Java component.
5-14
Microsoft Excel Add-In
To distribute an Excel add-in created with MATLAB Builder EX, create a package that includes the following files.
Software Module
componentname _version.dll
_install.bat
Description
Component that contains compiled MATLAB code
Script run by the self-extracting executable
Deploying to End Users
Software Module
MCRInstaller.exe
*.xla
Description
Self-extracting MATLAB Compiler Ru ntime library utility; platform-dependent file that must correspond to the end user’s platform
Any Excel a dd-in files found in
projectdirectory\distrib

Using Relative Paths with Project Files

Project files now support the use of relative paths as of R2007b of MATLAB Compiler, enabling you to share a single project file for convenient deployment over the network. Simply share your project folder and use relative paths to define your project location to your distributed computers.

Porting Generated Code to a Different Platform

You can distribu te an application generated by MATLAB Compiler to a ny targetmachinethathasthesameoperating system as the machine on which the application was compiled. For example, if you want to deploy an application to a Windows machine, you must use the Windows version of MATLAB Compiler to build the application on a Windows machine.
Note Since binary formats are different on each platform, the components generated by MATLAB Compiler cannot be moved from platform to platform as is.
To deploy an application to a machine with an operating system different from the machine used to develop the application, you must rebuild the application on the desired targeted platfo rm. For example, if you want to deploy a previous application developed on a Windows machine to a Linux machine, you must use MATL AB Compiler on a Linux machine and completely rebuild the application. You must have a valid MATLAB Compiler license on both platformstodothis.
5-15
5 Deployment Process
Extracting a CTF Component
CTF archives con extracted from archive you mu Default CTF Ar 6-20). To do this Not Embed CTF A
The CTF archi Compiler-ba applicatio library, CO
To expand a the
matlabroo
system ar
glnxa64,
and expan expands
extractCTF hello.ctf
noranapplicationthatcallsaMATLABCompiler-basedshared
extrac
t/toolbox/compiler/deploy/arch
chitecture, Windows =
and Mac OS X =
ds it into the folder in which it resides. For example, this command
hello.ctf into the folder where it resides:
tain content (MATLAB files and MEX-files) that need to be
the archive before they can be executed. In order to extract the
st override the default CTF embedding option (see “Overriding
chive Embedding Using the MCR Component Cache” on page
, ensure that you compile your component with the “-C Do
rchive by Default” on page 13-26 option.
ve automatically expands the first time you run a MATLAB
sed component (a MATLAB Compiler based standalone
M, or .NET component).
n archive without running the application, you can use
tCTF
(.exe on Windows) standalone utility provided in the
Archive Without Executing the
folder, where arch is your
win32|win64, Linux = glnx86,x86-64=
mac. This utility takes the CTF archive as input
5-16
The arc the f ol
compon
Note T
matla
vari MATL
Ens
If y use ma
hive expands into a folder called
der containing the expanded archive is
entname
orun
broot/toolbox/compiler/deploy/arch
able. Run
AB,besuretousethebang(
isthenameoftheCTFarchivewithouttheextension.
extractCTF from any folder, you must add
extractCTF.exe from a system prompt. If you run it from
uring Memory for Deployed Applications
ou are having trouble obtaining memory for your deployed application,
MATLAB Memory Shielding for deployed applications to ensure a
ximum amount of contiguous allocated memory . See “Reserving Memory
hello_mcr. In general, the name of
<componentname>_mcr,where
to your PATH environment
!) operator.
Deploying to End Users
for Deployed Applications with MATLAB Memory Shielding” on page 5-42 for more information.
5-17
5 Deployment Process

Working with the MCR

In this section...
“About the MATLAB®Compiler Runtime (MCR)” on page 5-18
“Installing the MCR and MATLAB on the Same Machine” on page 5-19
“Installing Multiple MCRs on One Machine” on page 5-21
“Retrieving MCR Attributes” on page 5-21
“Improving Data Access Using the MCR User Data Interface” on page 5-23
“Displaying MCR Initialization Start-Up and Completion Messages For Users” on page 5-37

About the MATLAB Compiler Runtime (MCR)

MATLAB Compiler uses the MATLAB Compiler Runtime (MCR), a standalone set of shared libraries that enables the execution of MATLAB files on computers without an installed version of MATLAB.
5-18
If you do not have MATLAB installed on the target machine and you want to run com ponents created by MATLAB Compiler , you still need to install the MCR on the target machine, whether you are a developer orenduser. YouhavetoinstalltheMCRonlyonce. Thereisnowayto distribute your application with any subset of the files that are installed by
MCRInstaller.exe.
See “Deploying to End Users” on page 5-9 for more information about the general steps for installing the MCR as part of the deployment process.
See also “Using M CR Installer Command Line Options” on page 11-9 for more information.
How is the MCR Different from MATLAB?
This MCR differs from MATLAB in several important ways:
In the MCR, MATLAB files are securely encrypted for portability and
integrity.
Working with the MCR
MATLAB has a desktop graphical interface. The MCR is has all of
MATLAB’s functionality without the graphical interface.
The MCR is version-specific. You must run your applications with the
version of the MCR associated with the version of MATLAB Compiler with which it was created. For example, if you compiled an application using version 4.10 (R2009a) of MATLAB Compiler, users who do not have MATLAB installed must have version 7.10 of the MCR installed. Use
mcrversion to return the version number of the MCR.
The MATLAB and Java paths in an M CR instance are fixed and cannot be
changed. To change them, you must first customize them within MATLAB.
Performance Considerations and the MCR
MATLAB Compiler was designed to work with a large range of applications that use the MATLAB programming language. Because of this, run-time libraries are large.
Since the MCR technology provides full support for the MATLAB language, including the Ja va programming language, starting a compiled application takes approximately the same amount of time as starting MATLAB. The amount of resources consumed by the MCR is necessary in order to retain the power and functionality ofafullversionofMATLAB.
The MCR makes use of thread locking so that only one thread is allowed to access the MCR at a time. As a result, calls into the MCR are threadsafe for MATLAB Compiler generated libraries, COM objects, and .NET objects. On the other hand, this can impact performance.

Installing the MCR and MATLAB on the Same Machine

You do not need to install the MCR on your machine if your machine has both MATLAB and MATLAB Compiler installed. The version of MATLAB should be the same as the version of MATLAB that was used to create the deployed component.
5-19
5 Deployment Process
Caution There is a limitation regarding folders on your path. If the
target machine has a MATLAB installation, the
<mcr_root> folders must
be first on the path to run the deployed application. To run MATLAB, the
matlabroot folders must be first on the path. This restriction only applies
to configurations involving an installed MCR and an installed MATLAB on the same machine.
Modifying the Path
If you install the MCR on a machine that already has MATLAB on it, you must adjust the library path according to your needs.
Windows. To run deployed components against the MCR install,
mcr_root\ver\runtime\win32|win64 must appear on your system path
before
If path, the application uses the files in the MCR install area.
matlabroot\runtime\win32|win64.
mcr_root\ver\runtime\arch appears first on the compiled application
5-20
If
matlabroot\runtime\arch appears first on the compiled application path,
the application uses the files in the MATLAB Compiler installation area.
UNIX. To run deployed components against the MCR install, on Linux, Linux x86-64, or the
LD_LIBRARY_PATH before mat labroot/runtime/<arch>,andXAPPLRESDIR
<mcr_root>/runtime/<arch> folder must appear on your
should point to <mcr_root>/X11/app-defaults. See “Directories Required for Run-Time Deployment” on page 11-5 for the platform-specific commands.
To run deployed components on Mac OS X, the
<mcr_root>/runtime
folder must appear on your DYLD_LIBRARY_PATH before
matlabroot/runtime/<arch>,andXAPPLRESDIR should point to <mcr_root>/X11/app-defaults.
TorunMATLABonMacOSXorIntel
®
Mac, ma tlabroot/runtime/<arch> must appear on your DYLD_LIBRARY_PATH before the <mcr_root>/bin folder, and
XAPPLRESDIR should point to matlabroot/X11/app-defaults.
Loading...