MATLAB Compiler The Language of Technical Computing Computation Visualization Programming User’s Guide Version 3
How to Contact The MathWorks: www.mathworks.com comp.soft-sys.matlab Web Newsgroup info@mathworks.com Technical support Product enhancement suggestions Bug reports Documentation error reports Order status, license renewals, passcodes Sales, pricing, and general information 508-647-7000 Phone 508-647-7001 Fax The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098 Mail support@mathworks.com suggest@mathworks.com bugs@mathworks.com doc@mathworks.com service@mathworks.
Contents Preface Related Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . x Using this Guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi Typographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . xii Introducing the MATLAB Compiler 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 Before You Begin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
COM Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16 Hiding Proprietary Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . 1-16 Upgrading from Previous Versions of the Compiler . . . . . 1-17 Upgrading from MATLAB Compiler 2.0/2.1/2.2/2.3 . . . . . . . . . 1-17 Upgrading from MATLAB Compiler 1.0/1.1 . . . . . . . . . . . . . . . 1-17 Limitations and Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . MATLAB Code . . . . . . . . . . . . . . . . . .
Working with MEX-Files 3 A Simple Example — The Sierpinski Gasket . . . . . . . . . . . . . 3-2 Compiling the M-File into a MEX-File . . . . . . . . . . . . . . . . . . . . 3-3 Invoking the MEX-File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4 Compiler Options and Macros . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6 Generating Simulink S-Functions . . . . . . . . . . . . . . . . . . . . . . 3-7 Simulink Specific Options . . . . . . . . . . . . . . . . . . . . . . . . . . .
Building Stand-Alone Applications on PCs . . . . . . . . . . . . . Configuring for C or C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Preparing to Compile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Verifying mbuild . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Verifying the MATLAB Compiler . . . . . . . . . . . . . . . . . . . . . . . About the mbuild Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Controlling Code Generation 5 Code Generation Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2 Example M-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2 Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3 Compiling Private and Method Functions . . . . . . . . . . . . . . . 5-5 The Generated Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8 C Header File . . . . . . . . . . . . . . . . . .
Interfacing M-Code to C/C++ Code . . . . . . . . . . . . . . . . . . . . . 5-46 C Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-46 Using Pragmas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-48 Optimizing Performance 6 Optimization Bundles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2 Optimizing Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Scalar Arrays . . . . . . . . .
MATLAB Compiler Quick Reference A Common Uses of the Compiler . . . . . . . . . . . . . . . . . . . . . . . . . A-2 mcc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4 Error and Warning Messages B Compile-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-2 Warning Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-11 Run-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . .
viii Contents
Preface This chapter provides information about this documentation set. The sections are as follows. Related Products (p. x) MathWorks products related to the Compiler Using this Guide (p. xi) An overview of this book Typographical Conventions (p.
Preface Related Products The MATLAB Compiler automatically converts MATLAB M-files to C and C++ code. The MATLAB Compiler includes the MATLAB C/C++ Math and Graphics Libraries, which let you automatically convert your MATLAB applications to C and C++ code for stand-alone applications. The MathWorks provides several products that are especially relevant to the MATLAB Compiler.
Using this Guide Using this Guide This book describes the MATLAB Compiler and provides numerous examples of how to use it. The topics included are • Introducing the MATLAB Compiler — describes the new features of the Compiler and provides an overview of how to use it. • Installation and Configuration — discusses how to install and configure the Compiler, and how to verify that your system is properly set up. • Working with MEX-Files — describes how to compile M-files with the MATLAB Compiler.
Preface Typographical Conventions This manual uses some or all of these conventions. Item Convention Example Example code Monospace font To assign the value 5 to A, enter A = 5 Function names, syntax, filenames, directory/folder names, user input, items in drop-down lists Monospace font The cos function finds the cosine of each array element. Buttons and keys Boldface with book title caps Press the Enter key.
1 Introducing the MATLAB Compiler This chapter describes the MATLAB Compiler and its uses. It also includes new features, upgrading information, and limitations and restrictions that you should know. Introduction (p. 1-2) A brief overview New Features (p. 1-4) Features added in this and previous releases Uses of the Compiler (p. 1-9) High-level descriptions of what the Compiler can do The MATLAB Compiler Family (p. 1-14) Pictorial view of the Compiler’s output Why Compile M-Files? (p.
1 Introducing the MATLAB Compiler Introduction This book describes Version 3.0 of the MATLAB® Compiler. The MATLAB Compiler takes M-files as input and generates C or C++ source code or P-code as output. The MATLAB Compiler can generate these kinds of source code: • C source code for building MEX-files. • C or C++ source code for combining with other modules to form stand-alone applications.
Introduction Note The phrase MATLAB interpreter refers to the application that accepts MATLAB commands, executes M-files and MEX-files, and behaves as described in the Using MATLAB documentation. When you use MATLAB, you are using the MATLAB interpreter. The phrase MATLAB Compiler refers to this product, which translates M-files to C or C++ source code and its associated libraries. This book distinguishes references to the MATLAB Compiler by using the word ‘Compiler’ with a capital C.
1 Introducing the MATLAB Compiler New Features MATLAB Compiler 3.0 • The MATLAB Compiler now includes the MATLAB C/C++ Math and Graphics Libraries. Note As the MATLAB Compiler evolves, it will support additional standard platform interfaces such as COM, Java, and CORBA. Consequently, the requirement of developing code specifically for the MATLAB C/C++ Math Library will diminish. Once this happens, the Math Library will no longer support code written directly for the Library.
New Features • The new option, -b, causes the Compiler to generate a Visual Basic (.bas) file that contains the Microsoft Excel Formula Function interface to a Compiler-generated COM object. • The new option, -i, causes the Compiler to include only the M-files that are specified on the command line as exported interfaces. Note To create Microsoft Excel components with the MATLAB Compiler, you must have the MATLAB Excel Builder product installed on your system. MATLAB Compiler 2.1 MATLAB Compiler 2.
1 Introducing the MATLAB Compiler Conditional Expressions. Reduces the MATLAB conditional operators to scalar C conditional operators when both operands are known to be integer scalars. For more information on these optimizations, see Chapter 6, “Optimizing Performance.” mlib Files mlib files make it possible to produce a shared library out of a toolbox and then compile M-files that make calls into that toolbox.
New Features Faster C/C++ Math Library Applications The improved performance of the C/C++ Math Library is due in part to the added scalar accelerated versions of many of the library functions. Additional Language Support pause and continue. These commands are now supported. eval and input. eval and input are supported for strings that do not contain workspace variables. Note As of Compiler 2.1, Compiler 1.2 is no longer available due to the evolution of internal data structures. The -V1.
1 Introducing the MATLAB Compiler Running Compiler from DOS/UNIX Shell If you run the Compiler from a DOS or UNIX shell, you are running from “outside” of MATLAB.
Uses of the Compiler Uses of the Compiler The MATLAB Compiler (mcc) can translate M-files into C files. The resultant C files can be used in any of the supported executable types including MEX, executable, or library by generating an appropriate wrapper file. A wrapper file contains the required interface between the Compiler-generated code and a supported executable type.
1 Introducing the MATLAB Compiler M-File mcc -x • Shaded block is user-written code. C version of M code C MEX-File Wrapper mex • Shadowed blocks are MathWorks tools. • Unshaded blocks are MATLAB Compiler-generated code. • Dotted block is C/C++ compiler-generated executable. MEX Math Library (libmatlbmx) MEX-File Figure 1-1: Developing MEX-Files MATLAB users who do not have the MATLAB Compiler must write the source code for MEX-files in either Fortran or C.
Uses of the Compiler Creating Stand-Alone Applications C Stand-Alone Applications The MATLAB Compiler, when invoked with the -m macro option, translates input M-files into C source code that is usable in any of the supported executable types. The Compiler also produces the required wrapper file suitable for a stand-alone application.
1 Introducing the MATLAB Compiler M-File function to find the rank of a magic square mcc -m • Shaded block is user-written code. mbuild does this part. C version of M code C File Wrapper • Shadowed blocks are tools. • Unshaded blocks are MATLAB Compiler-generated code. C Compiler • Dotted blocks are C/C++ compiler-generated executables.
Uses of the Compiler See Chapter 4, “Stand-Alone Applications” for complete details regarding stand-alone applications. Figure 1-2, Developing a Typical Stand-Alone C Application, illustrates the process of developing a typical stand-alone C application. Use the same basic process for developing stand-alone C++ applications, but use the -p option instead of the -m option with the MATLAB Compiler and a C++ compiler instead of a C compiler.
1 Introducing the MATLAB Compiler The MATLAB Compiler Family This figure illustrates the various ways you can use the MATLAB Compiler. The shaded blocks represent user-written code; the unshaded blocks represent Compiler-generated code; the remaining blocks (drop shadow) represent MathWorks or other vendor tools.
The MATLAB Compiler Family The Compiler takes your M-file(s) and can generate C or C++ code. It can also generate a wrapper file depending on your specified target. This table shows the wrapper files the Compiler can generate, their associated targets, and the corresponding -W option (wrapper).
1 Introducing the MATLAB Compiler Why Compile M-Files? There are several reasons to compile M-files: • To create stand-alone applications • To create C shared libraries (DLLs on Windows) or C++ static libraries • To create COM components • To hide proprietary algorithms Stand-Alone Applications and Libraries You can create MATLAB applications that take advantage of the mathematical functions of MATLAB, yet do not require that the user owns MATLAB.
Upgrading from Previous Versions of the Compiler Upgrading from Previous Versions of the Compiler MATLAB Compiler 3.0 is fully compatible with previous releases of the Compiler. If you have your own M-files that were compiled with a previous version of the Compiler and compile them with the new version, you will get the same results. Upgrading from MATLAB Compiler 2.0/2.1/2.2/2.3 MATLAB Compiler 2.1 (and later versions) does not support the -V1.2 option that was available in Compiler 2.0.
1 Introducing the MATLAB Compiler Limitations and Restrictions MATLAB Code MATLAB Compiler 3.0 supports almost all of the functionality of MATLAB. However, there are some limitations and restrictions that you should be aware of. This version of the Compiler cannot compile • Script M-files (See “Converting Script M-Files to Function M-Files” on page 3-10 for further details.
Limitations and Restrictions if (y==3) persistent x else x = 3; end Stand-Alone Applications The restrictions and limitations noted in the previous section also apply to stand-alone applications. The functions in Table 1-2, Unsupported Functions in Stand-Alone Mode, are supported in MEX-mode, but are not supported in stand-alone mode. Note Stand-alone applications cannot access Simulink functions.
1 Introducing the MATLAB Compiler Table 1-2: Unsupported Functions in Stand-Alone Mode (Continued) javaMethod javaObject keyboard linmod lookfor macprint mactools methods mislocked mlock more munlock new_system open_system pack pfile rehash runtime set_param sim simget simset sldebug str2func superiorto system_dependent trmginput type vms what which who whos Fixing Callback Problems: Missing Functions When the Compiler creates a stand-alone application, it compiles the M-f
Limitations and Restrictions in callback strings.) The Compiler processes any function listed in a %#function pragma. For example, the call to the change_colormap function in the sample application, my_test, illustrates this problem. To make sure the Compiler processes the change_colormap M-file, list the function name in the %#function pragma: function my_test() % Graphics library callback test application %#function change_colormap peaks; p_btn = uicontrol(gcf,... 'style', 'pushbutton',...
1 Introducing the MATLAB Compiler 1-22
2 Installation and Configuration This chapter describes the system requirements for the MATLAB Compiler and installation and configuration information. It includes information for both MATLAB Compiler platforms — UNIX and Microsoft Windows. When you install your ANSI C or C++ compiler, you may be required to provide specific configuration details regarding your system. This chapter contains information for each platform that can help you during this phase of the installation process.
2 Installation and Configuration System Configuration for MEX-Files This section outlines the steps necessary to configure your system to create MEX-files. The sequence of steps to install and configure the MATLAB Compiler so that it can generate MEX-files is 1 Install the MATLAB Compiler. 2 Install an ANSI C or C++ compiler, if you don’t already have one installed.
System Configuration for MEX-Files Start Install MATLAB Compiler Install ANSI C/ C++ Compiler Use MATLAB installer to install component (MATLAB Compiler). Is ANSI C or C++ compiler installed ? No Follow vendor’s instructions to install and test ANSI C or C++ compiler. Yes Verify mex Test your mex configuration. 1 Does the MATLAB command mex yprime.c generate proper MEX-file No ? See “mex Troubleshooting.
2 Installation and Configuration UNIX Workstation This section examines the system requirements, installation procedures, and configuration procedures for the MATLAB Compiler on UNIX systems. System Requirements You cannot install the MATLAB Compiler unless MATLAB 6.5 (Release 13) is already installed on the system. The MATLAB Compiler imposes no operating system or memory requirements beyond those that are necessary to run MATLAB. The MATLAB Compiler consumes a small amount of disk space.
UNIX Workstation Note For a list of all the compilers supported by MATLAB, see the MathWorks Technical Support Department’s Technical Notes at http://www.mathworks.com/support/tech-notes/1600/1601.shtml Known Compiler Limitations. There are several known restrictions regarding the use of supported compilers: • The SGI C compiler does not handle denormalized floating-point values correctly.
2 Installation and Configuration shows the preconfigured options files that are included with MATLAB for UNIX. Compiler Options File System native ANSI compiler mexopts.sh gcc (GNU C compiler) gccopts.sh Information on the options files is provided for those users who may need to modify them to suit their own needs. Many users never have to be concerned with the inner workings of the options files.
UNIX Workstation ANSI C or C++ Compiler To install your ANSI C or C++ compiler, follow the vendor’s instructions that accompany your C or C++ compiler. Be sure to test the C or C++ compiler to make sure it is installed and configured properly. Typically, the compiler vendor provides some test procedures. The following section, “Things to Be Aware of,” contains several UNIX-specific details regarding the installation and configuration of your ANSI C or C++ compiler.
2 Installation and Configuration If you do not need to change C or C++ compilers, or you do not need to modify your compiler options files, you can skip ahead in this section to “Creating MEX-Files” on page 2-9. If you need to know how to change the options file, continue with this section. Changing Compilers Changing the Default Compiler. To change your default C or C++ compiler, you select a different options file.
UNIX Workstation Note The setup option creates a user-specific, matlab directory in your individual home directory and copies the appropriate options file to the directory. (If the directory already exists, a new one is not created.) This matlab directory is used for your individual options files only; each user can have his or her own default options files (other MATLAB products may place options files in this directory).
2 Installation and Configuration On UNIX, MEX-files are created with platform-specific extensions, as shown in Table 2-2, MEX-File Extensions for UNIX. Table 2-2: MEX-File Extensions for UNIX Platform MEX-File Extension Dec/Compaq Alpha mexaxp HP 9000 PA-RISC mexhp7 HP-UX mexhpux IBM RS/6000 mexrs6 Linux mexglx SGI mexsg Solaris mexsol The /extern/examples/mex directory contains C source code for the example yprime.c. After you copy the source file (yprime.
UNIX Workstation MATLAB Compiler Verification Verifying from MATLAB Once you have verified that you can generate MEX-files on your system, you are ready to verify that the MATLAB Compiler is correctly installed. Type the following at the MATLAB prompt. mcc -x invhilb After a short delay, this command should complete and display the MATLAB prompt.
2 Installation and Configuration Next, verify that invhilb is now a MEX-file by listing the invhilb files: ls invhilb.* You will see a list similar to this: invhilb.c invhilb.h invhilb.m invhilb.mexsol invhilb_mex.c These are the various files that the Compiler generates from the M-file. The Compiler-generated MEX-file appears in the list as the filename followed by the appropriate UNIX MEX-file extension. In this example, the Compiler was executed on Solaris, so the Compiler creates the file invhilb.
Microsoft Windows on PCs Microsoft Windows on PCs This section examines the system requirements, installation procedures, and configuration procedures for the MATLAB Compiler on PCs running Microsoft Windows. System Requirements You cannot install the MATLAB Compiler unless MATLAB 6.5 (Release 13) is already installed on the system. The MATLAB Compiler imposes no operating system or memory requirements beyond what is necessary to run MATLAB. The MATLAB Compiler consumes a small amount of disk space.
2 Installation and Configuration Supported ANSI C and C++ PC Compilers To create C MEX-files, stand-alone C/C++ applications, or dynamically linked libraries (DLLs) with the MATLAB Compiler, you must install and configure a supported C/C++ compiler. Use one of the following 32-bit C/C++ compilers that create 32-bit Windows dynamically linked libraries (DLLs) or Windows NT applications: • Lcc C version 2.4 (included with MATLAB). This is a C only compiler; it does not work with C++.
Microsoft Windows on PCs Known Compiler Limitations. There are several known restrictions regarding the use of supported compilers: • Some compilers, e.g., Watcom, do not handle denormalized floating-point values correctly. Denormalized floating-point numbers are numbers that are greater than 0 and less than the value of DBL_MIN in your compiler’s float.h file. • The MATLAB Compiler sometimes will generate goto statements for complicated if conditions.
2 Installation and Configuration Compiler Options Files The MathWorks provides options files for every supported C or C++ compiler. These files contain the necessary flags and settings for the compiler. This table shows the preconfigured PC options files that are included with MATLAB. Compiler Options File Lcc C, Version 2.4 (included with MATLAB) lccopts.bat Microsoft Visual C/C++, Version 5.0 Microsoft Visual C/C++, Version 6.0 Microsoft Visual C/C++, Version 7.0 msvc50opts.bat msvc60opts.
Microsoft Windows on PCs created during the -setup process, in a subdirectory of your user profile directory, named Application Data\MathWorks\MATLAB\R13. Under Windows with user profiles enabled, your user profile directory is %windir%\Profiles\username. Under Windows with user profiles disabled, your user profile directory is %windir%. You can determine whether or not user profiles are enabled by using the Passwords control panel.
2 Installation and Configuration Things to Be Aware of This table provides information regarding the installation and configuration of a C/C++ compiler on your system. 2-18 Description Comment Installation options We recommend that you do a full installation of your compiler. If you do a partial installation, you may omit a component that the MATLAB Compiler relies on. Installing debugger files For the purposes of the MATLAB Compiler, it is not necessary to install debugger (DBG) files.
Microsoft Windows on PCs mex Verification Choosing a Compiler Systems with Exactly One C/C++ Compiler. If you have properly installed the MATLAB Compiler and your supported C or C++ compiler, you can now create C MEX-files. On systems where there is exactly one C or C++ compiler available to you, the mex utility automatically configures itself for the appropriate compiler. So, for many users, to create a C MEX-file, you can simply enter mex filename.
2 Installation and Configuration [1] : Borland compiler in T:\Borland\BC.500 [2] : WATCOM compiler in T:\watcom\c.106 [0] : None Please select a compiler. This compiler will become the default: Select the desired compiler by entering its number and pressing Return. You are then asked to verify the information. Changing Compilers Changing the Default Compiler. To change your default C or C++ compiler, you select a different options file. You can do this at any time by using the mex -setup option.
Microsoft Windows on PCs [15] Microsoft Visual C/C++ version 5.0 [16] WATCOM C/C++ version 11 [17] WATCOM C/C++ version 10.6 [0] None Compiler: 14 Your machine has a Microsoft Visual C/C++ compiler located at D:\Applications\Microsoft Visual Studio. Do you want to use this compiler [y]/n? y Please verify your choices: Compiler: Microsoft Visual C/C++ 6.
2 Installation and Configuration The setup option copies the appropriate options file to your user profile directory. To make your user-specific changes to the options file, you edit your copy of the options file in your user profile directory to correspond to your specific needs and save the modified file. After completing this process, the mex script will use the new options file everytime with your modified settings. Temporarily Changing the Compiler.
Microsoft Windows on PCs mex -setup and select Microsoft Visual C/C++ version 5 or 6. For more information about the add-in, see “Using an Integrated Development Environment” on page 4-23. Note The MATLAB add-in for Visual Studio does not currently work with Microsoft Visual C/C++, Version 7.0. MATLAB Compiler Verification Verifying from MATLAB Once you have verified that you can generate MEX-files on your system, you are ready to verify that the MATLAB Compiler is correctly installed.
2 Installation and Configuration Note Before you test to see if the Compiler can generate MEX-files from the DOS command prompt, you may want to delete the MEX-file you created in the previous section, invhilb.dll. That way, you can be sure your newly generated MEX-file is the result of using the Compiler from the DOS prompt. To delete this file, you must clear the MEX-file or quit MATLAB; otherwise the deletion will fail. Copy invhilb.
Troubleshooting Troubleshooting This section identifies some of the more common problems that can occur when installing and configuring the MATLAB Compiler. mex Troubleshooting Out of Environment Space Running mex or mbuild. On Windows 98 systems, the mex and mbuild scripts require more than the default amount of environment space. If you get the error, out of environment space, add this line to your config.sys file. shell=c:\command.
2 Installation and Configuration mex Works from Shell But Not from MATLAB (UNIX). If the command mex -x yprime.c works from the UNIX shell prompt but does not work from the MATLAB prompt, you may have a problem with your .cshrc file. When MATLAB launches a new C shell to perform compilations, it executes the .cshrc script. If this script causes unexpected changes to the PATH, an error may occur. You can test whether this is true by performing a set SHELL=/bin/sh prior to launching MATLAB.
Troubleshooting Troubleshooting the Compiler One problem that might occur when you try to use the Compiler involves licensing. Licensing Problem. If you do not have a valid license for the MATLAB Compiler, you will get an error message similar to the following when you try to access the Compiler. Error: Could not check out a Compiler License: No such feature exists. If you have a licensing problem, contact The MathWorks. A list of contacts at The MathWorks is provided at the beginning of this manual.
2 Installation and Configuration 2-28
3 Working with MEX-Files This chapter gets you started compiling M-files with the MATLAB Compiler. A Simple Example — The Sierpinski Gasket (p. 3-2) Creating a MEX-file from an M-file Compiler Options and Macros (p. 3-6) Overview of options and macros Generating Simulink S-Functions (p. 3-7) Generating Simulink C MEX S-functions Converting Script M-Files to Function M-Files (p.
3 Working with MEX-Files A Simple Example — The Sierpinski Gasket Consider an M-file function called gasket.m: function theImage = gasket(numPoints) %GASKET An image of a Sierpinski Gasket. % IM = GASKET(NUMPOINTS) % % Example: % x = gasket(50000); % imagesc(x);colormap([1 1 1;0 0 0]); % axis equal tight % % Copyright (c) 1984-98 by The MathWorks, Inc $Revision: 1.
A Simple Example — The Sierpinski Gasket The curve can be graphed in many ways. Sierpinski's method is • Start with a triangle and from it remove a triangle that is one-half the height of the original and inverted. This leaves three triangles. • From each of the remaining three triangles, remove a triangle that is one-fourth the height of these new triangles and inverted. This leaves nine triangles.
3 Working with MEX-Files This example uses the -x macro option to create the MEX-file. For more information on this Compiler option, see the mcc reference page. For more information on the files that the Compiler generates, see Chapter 5, “Controlling Code Generation.” Invoking the MEX-File Invoke the MEX-file version of gasket from the MATLAB interpreter the same way you invoke the M-file version. x = gasket(50000); MATLAB runs the MEX-file version (gasket.mex, which is gasket.
A Simple Example — The Sierpinski Gasket Figure 3-1, The Sierpinski Gasket for 50,000 Points, shows the results.
3 Working with MEX-Files Compiler Options and Macros The MATLAB Compiler uses a family of options, also called option flags, to control the functionality of the Compiler. The mcc reference page includes a complete description of the Compiler options. Throughout this book you will see how these options are used with the Compiler to perform various tasks. One particular set of Compiler options, macros, are particularly useful for performing straightforward compilations.
Generating Simulink S-Functions Generating Simulink S-Functions You can use the MATLAB Compiler to generate Simulink C MEX S-functions. This allows you to speed up Simulink models that contain MATLAB M-code that is referenced from a MATLAB Fcn block. Note Only the MATLAB Fcn block is supported. For more information about Simulink in general, see the Simulink documentation. For more information about Simulink S-functions, see “Writing S-Functions” in the Simulink documentation.
3 Working with MEX-Files The result is an S-function described in the following files: mfilename.c mfilename.h mfilename_simulink.c mfilename.ext (where ext is the MEX-file extension for your platform, e.g., dll for Windows) Using the -u and -y Options Using the -S option by itself will generate code suitable for most general applications. However, if you would like to exert more control over the number of valid inputs or outputs for your function, you should use the -u and/or -y options.
Generating Simulink S-Functions Data Type The input and output vectors for the Simulink S-function must be double-precision vectors or scalars. You must ensure that the variables you use in the M-code for input and output are also double-precision values. Note Simulink S-functions that are generated via the -S option of the Compiler are not currently compatible with Real-Time Workshop®. They can, however, be used to rapidly prototype code in Simulink.
3 Working with MEX-Files Converting Script M-Files to Function M-Files MATLAB provides two ways to package sequences of MATLAB commands: • Function M-files • Script M-files These two categories of M-files differ in two important respects: • You can pass arguments to function M-files but not to script M-files. • Variables used inside function M-files are local to that function; you cannot access these variables from the MATLAB interpreter’s workspace unless they are passed back by the function.
Converting Script M-Files to Function M-Files in the MATLAB workspace.
3 Working with MEX-Files 3-12
4 Stand-Alone Applications This chapter explains how to use the MATLAB Compiler to code and build stand-alone applications. Stand-alone applications run without the help of the MATLAB interpreter. In fact, stand-alone applications run even if MATLAB is not installed on the system. However, stand-alone applications do require the run-time shared libraries, which are detailed in the corresponding sections. Differences Between MEX-Files and Stand-Alone Applications (p.
4 Stand-Alone Applications Differences Between MEX-Files and Stand-Alone Applications MEX-files and stand-alone applications differ in these respects: • MEX-files run in the same process space as the MATLAB interpreter. When you invoke a MEX-file, the MATLAB interpreter dynamically links in the MEX-file. • Stand-alone C or C++ applications run independently of MATLAB. MEX-Files It is now possible to call MEX-files from Compiler-generated stand-alone applications.
Differences Between MEX-Files and Stand-Alone Applications For more information about distributing a C application, see “Distributing Stand-Alone Applications” on page 4-27. Note If you attempt to compile M-files to produce stand-alone applications and you do not have the MATLAB C/C++ Math Library installed, the system will not be able to find the appropriate libraries and the linking will fail.
4 Stand-Alone Applications Building Stand-Alone C/C++ Applications This section explains how to build stand-alone C and C++ applications on UNIX systems and PCs running Microsoft Windows. This section begins with a summary of the steps involved in building stand-alone C/C++ applications, including the mbuild script, which helps automate the build process, and then describes platform-specific issues for both supported platforms.
Building Stand-Alone C/C++ Applications Figure 4-1, Sequence for Creating Stand-Alone C/C++ Applications, shows the sequence on both platforms. The sections following the flowchart provide more specific details for the individual platforms. Start 1 Verify mbuild Test your mbuild configuration. Does the command mbuild ex1.c generate proper application No ? See “Troubleshooting mbuild.” Yes 2 1 Verify MATLAB Compiler can generate application Test your MATLAB Compiler configuration.
4 Stand-Alone Applications Getting Started Introducing mbuild The MathWorks utility, mbuild, lets you customize the configuration and build process. The mbuild script provides an easy way for you to specify an options file that lets you • Set your compiler and linker settings • Change compilers or compiler settings • Switch between C and C++ development • Build your application The MATLAB Compiler (mcc) automatically invokes mbuild under certain conditions.
Building Stand-Alone Applications on UNIX Building Stand-Alone Applications on UNIX This section explains how to compile and link C or C++ source code into a stand-alone UNIX application.
4 Stand-Alone Applications Locating Options Files mbuild locates your options file by searching the following: • The current directory • $HOME/.matlab/R13 • /bin mbuild uses the first occurrence of the options file it finds. If no options file is found, mbuild displays an error message. Preparing to Compile Note Refer to “Supported ANSI C and C++ UNIX Compilers” on page 2-4 for information about supported compilers and important limitations.
Building Stand-Alone Applications on UNIX The setup option creates a user-specific options file for your ANSI C or C++ compiler. Executing mbuild -setup presents a list of options files currently included in the bin subdirectory of MATLAB: mbuild -setup Using the 'mbuild -setup' command selects an options file that is placed in ~/.matlab/R13 and used by default for 'mbuild'. An options file in the current working directory or specified on the command line overrides the default options file in ~/.
4 Stand-Alone Applications the current linker settings, or you want to disable a particular set of warnings, you should use the setup option. If you need to change the options that mbuild passes to your compiler or linker, you must first run mbuild -setup which copies a master options file to your local MATLAB directory, typically $HOME/.matlab/R13/mbuildopts.sh.
Building Stand-Alone Applications on UNIX Verifying mbuild There is C source code for an example ex1.c included in the /extern/examples/cmath directory, where represents the top-level directory where MATLAB is installed on your system. To verify that mbuild is properly configured on your system to create stand-alone applications, copy ex1.c to your local directory and type cd to change to that directory. Then, at the MATLAB prompt, enter mbuild ex1.c This creates the file called ex1.
4 Stand-Alone Applications be found and loaded. Consequently, to share a Compiler-generated, stand-alone application with another user, you must provide all of the required shared libraries. For more information about the required shared libraries for UNIX, see “Packaging UNIX Applications” on page 4-13. Running Your Application To launch your application, enter its name on the command line. For example: ex1 ans = 1 2 3 4 5 6 ans = 1.0000 + 7.0000i 2.0000 + 8.0000i 3.0000 + 9.0000i 4.0000 +10.
Building Stand-Alone Applications on UNIX About the mbuild Script The mbuild script supports various options that allow you to customize the building and linking of your code. Many users do not need to know any additional details of the mbuild script; they use it in its simplest form. For complete information about the mbuild script and its options, see the mbuild reference page.
4 Stand-Alone Applications Note If you distribute an application created with the math libraries on Digital UNIX, your users must have both the C++ and Fortran run-time shared libraries installed on their systems.
Building Stand-Alone Applications on PCs Building Stand-Alone Applications on PCs This section explains how to compile and link the C/C++ code generated from the MATLAB Compiler into a stand-alone Windows application.
4 Stand-Alone Applications Note You can override the language choice that is determined from the extension by using the -lang option of mbuild. For more information about this option, as well as all of the other mbuild options, see the mbuild reference page.
Building Stand-Alone Applications on PCs Choosing a Compiler Systems with Exactly One C/C++ Compiler. If the MATLAB Compiler and your supported C or C++ compiler are installed on your system, you are ready to create C or C++ stand-alone applications. On systems where there is exactly one C or C++ compiler available to you, the mbuild utility automatically configures itself for the appropriate compiler. So, for many users, to create a C or C++ stand-alone applications, you can simply enter mbuild filename.
4 Stand-Alone Applications [1] Lcc C version 2.4 in D:Applications\Mathworks\sys\lcc [2] Microsoft Visual C/C++ version 6.0 in D:\Applications\Microsoft Visual Studio [0] None Compiler: Select the desired compiler by entering its number and pressing Return. You are then asked to verify your information. Changing Compilers Changing the Default Compiler. To change your default C or C++ compiler, you select a different options file. You can do this at anytime by using the setup command.
Building Stand-Alone Applications on PCs Compiler: 10 Your machine has a Microsoft Visual C/C++ compiler located at D:\Applications\Microsoft Visual Studio. Do you want to use this compiler [y]/n? y Please verify your choices: Compiler: Microsoft Visual C/C++ 6.0 Location: D:\Applications\Microsoft Visual Studio Are these correct?([y]/n): y The default options file: "C:\WINNT\Profiles\username\ Application Data\MathWorks\MATLAB\R13\compopts.bat" is being updated...
4 Stand-Alone Applications specific needs and save the modified file. This sets your default compiler’s options file to your specific version. Table 4-3, Compiler Options Files on the PC, lists the names of the PC options files included in this release of MATLAB. If you need to see which options mbuild passes to your compiler and linker, use the verbose option, -v, as in mbuild -v filename1 [filename2 ...] to generate a list of all the current compiler settings used by mbuild.
Building Stand-Alone Applications on PCs Table 4-3: Compiler Options Files on the PC (Continued) Compiler Master Options File Microsoft Visual C/C++, Version 6.0 msvc60compp.bat Microsoft Visual C/C++, Version 7.0 msvc70compp.bat Combining Customized C and C++ Options Files. The options files for mbuild have changed as of MATLAB 5.3 (Release 11) so that the same options file can be used to create both C and C++ stand-alone applications.
4 Stand-Alone Applications Verifying mbuild There is C source code for an example, ex1.c, included in the \extern\examples\cmath directory, where represents the top-level directory where MATLAB is installed on your system. To verify that mbuild is properly configured on your system to create stand-alone applications, enter at the MATLAB prompt mbuild ex1.c This creates the file called ex1.exe.
Building Stand-Alone Applications on PCs 1.0000 + 7.0000i 2.0000 + 8.0000i 3.0000 + 9.0000i 4.0000 +10.0000i 5.0000 +11.0000i 6.0000 +12.0000i Verifying the MATLAB Compiler There is MATLAB code for an example, hello.m, included in the \extern\examples\compiler directory. To verify that the MATLAB Compiler can generate stand-alone applications on your system, type the following at the MATLAB prompt. mcc -m hello.m This command should complete without errors.
4 Stand-Alone Applications Note The MATLAB add-in for Visual Studio does not currently work with Microsoft Visual C/C++, Version 7.0. The add-in for Visual Studio is automatically installed on your system when you run either mbuild -setup or mex -setup and select Microsoft Visual C/C++ version 5 or 6.
Building Stand-Alone Applications on PCs your MATLAB path. If you add directories to your MATLAB path and want them to be visible to the MATLAB add-in, rerun the cd and mccsavepath commands shown in this step and replace prefdir with the desired pathname. 4 To configure the MATLAB add-in for Visual Studio to work with Microsoft Visual C/C++: a Select Tools -> Customize from the MSVC menu. b Click on the Add-ins and Macro Files tab.
4 Stand-Alone Applications • See the MATLABAddin.hlp file in the \bin\win32 directory, or • Click on the Help icon in the MATLAB add-in for Visual Studio toolbar Help Icon Packaging Windows Applications for Distribution To distribute a stand-alone Windows application, you must create a package containing these files: • Your application executable. • The contents, if any, of a directory named bin, created by mbuild in the same directory as your application executable.
Distributing Stand-Alone Applications Distributing Stand-Alone Applications To make packaging an application easier, all the necessary MATLAB run-time libraries are prepackaged into a single, self-extracting archive file. For more information about how you can use this archive, see “Packaging the MATLAB Run-Time Libraries”. For information about how customers who receive your application can use this archive, see “Installing Your Application” on page 4-27.
4 Stand-Alone Applications Note If customers already have the MATLAB math and graphics run-time libraries installed on their system, they do not need to reinstall them. They only need to ensure that the library search path is configured correctly. On UNIX Systems On UNIX systems, your customers run the MATLAB Compiler Run-Time Library Installer by executing the mglinstaller command at the system prompt. Your customers can specify the name of the directory into which they want to install the libraries.
Distributing Stand-Alone Applications The ordinal #### could not be located in the dynamic-link library dforrt.dll. To fix this problem, locate dforrt.dll or dformd.dll in your Windows system directory and replace them with the corresponding files in the \bin\win32 directory, where represents the name of your MATLAB installation directory. This same solution works for customers of your application who encounter the same problem.
4 Stand-Alone Applications Building Shared Libraries You can use mbuild to build C shared libraries on both UNIX and the PC. All of the mbuild options that pertain to creating stand-alone applications also pertain to creating C shared libraries. To create a C shared library, specify one or more files with the .exports extension. The .exports files are text files that contain the names of the functions to export from the shared library, one per line.
Building COM Objects Building COM Objects Note To create COM components from the MATLAB Compiler, you must have the MATLAB COM Builder installed on your system. You can use mbuild to create Component Object Model (COM) objects from MATLAB M-files. The collection of M-files is translated into a single COM class. MATLAB COM Builder supports multiple classes per component.
4 Stand-Alone Applications Building Excel Plug-Ins Note To create Excel plug-ins from the MATLAB Compiler, you must have the MATLAB Excel Builder installed on your system. You can use mbuild to create a COM object from MATLAB M-files that can be used as an Excel plug-in. The collection of M-files is translated into a single Excel plug-in. MATLAB Excel Builder supports one class per component.
Troubleshooting Troubleshooting Troubleshooting mbuild This section identifies some of the more common problems that might occur when configuring mbuild to create stand-alone applications. Options File Not Writeable. When you run mbuild -setup, mbuild makes a copy of the appropriate options file and writes some information to it. If the options file is not writeable, you are asked if you want to overwrite the existing options file.
4 Stand-Alone Applications mbuild Works from Shell but Not from MATLAB (UNIX). If the command mbuild ex1.c works from the UNIX command prompt but does not work from the MATLAB prompt, you may have a problem with your .cshrc file. When MATLAB launches a new C shell to perform compilations, it executes the .cshrc script. If this script causes unexpected changes to the PATH environment variable, an error may occur. You can test this by performing a set SHELL=/bin/sh prior to launching MATLAB.
Troubleshooting Troubleshooting the Compiler Typically, problems that occur when building stand-alone C and C++ applications involve mbuild. However, it is possible that you may run into some difficulty with the MATLAB Compiler. One problem that might occur when you try to generate a stand-alone application involves licensing. Licensing Problem.
4 Stand-Alone Applications Coding with M-Files Only One way to create a stand-alone application is to write all the source code in one or more M-files or MEX-files. Coding an application in M-files allows you to take advantage of the MATLAB interpretive development environment. Then, after getting the M-file version of your program working properly, compile the code and build it into a stand-alone application.
Coding with M-Files Only The -m option flag causes the MATLAB Compiler to generate C source code suitable for stand-alone applications. For example, the MATLAB Compiler generates C source code files main.c, main_main.c, and mrank.c. main_main.c contains a C function named main; main.c and mrank.c contain a C functions named mlfMain and mlfMrank. (The -c option flag inhibits invocation of mbuild.) To build an executable application, you can use mbuild to compile and link these files.
4 Stand-Alone Applications mbuild does main.m mrank.m mcc -W main -t main mcc -t mrank.m main_main.c main.c mrank.c this part. C Compiler C Compiler Object File Object File MATLAB M-File Math Library MATLAB API Library MATLAB Math Built-In Library MATLAB Utility Library ANSI C Library MATLAB C/C++ Graphics Library • Shaded blocks are user-written code. Linker • Shadowed blocks are tools. • Unshaded blocks are MATLAB Compiler-generated code.
Coding with M-Files Only For C++ code, add -L cpp to the previous commands and use a C++ compiler instead of a C compiler.
4 Stand-Alone Applications Alternative Ways of Compiling M-Files The previous section showed how to compile main.m and mrank.m separately. This section explores two other ways of compiling M-files. Note These two alternative ways of compiling M-files apply to C++ as well as to C code; the only difference is that you add -L cpp for C++. Compiling MATLAB Provided M-Files Separately The M-file mrank.m contains a call to rank. The MATLAB Compiler translates the call to rank into a C call to mlfRank.
Alternative Ways of Compiling M-Files mcc -m main_main.c main.c rank.c mrank.c The resulting stand-alone application uses your customized version of mlfRank rather than the default version of mlfRank stored in the MATLAB M-File Math Library. Note On PCs running Windows, as well as SGI, SGI64, and IBM, if a function in the MATLAB M-File Math Library calls mlfRank, it will call the one found in the Library and not your customized version.
4 Stand-Alone Applications Mixing M-Files and C or C++ The examples in this section illustrate how to mix M-files and C or C++ source code files: • The first example is a simple application that mixes M-files and C code. • The second example illustrates how to write C code that calls a compiled M-file. One way to create a stand-alone application is to code some of it as one or more function M-files and to code other parts directly in C or C++.
Mixing M-Files and C or C++ The Build Process The steps needed to build this stand-alone application are 1 Compile the M-code. 2 Generate the library wrapper file. To perform these steps, use mcc -t -W lib:Pkg -T link:exe -h mrank mrankp.c libmmfile.mlib The MATLAB Compiler generates C source code files named mrank.c, Pkg.c, and Pkg.h. This command invokes mbuild to compile the resulting Compiler-generated source files (mrank.c, Pkg.c, Pkg.h) with the existing C source file (mrankp.
4 Stand-Alone Applications mrank.m mcc -t -W lib:Pkg -T link:exe mrank mrankp.c mbuild does mrankp.c mrank.c, Pkg.c, Pkg.h C Compiler C Compiler Object File Object File this part. MATLAB M-File Math Library MATLAB API Library MATLAB Math Built-In Library MATLAB Utility Library ANSI C Library MATLAB C/C++ Graphics Library • Shaded blocks are user-written code. Linker • Shadowed blocks are tools. • Unshaded blocks are MATLAB Compiler-generated code.
Mixing M-Files and C or C++ mrankp.c The code in mrankp.c calls mrank and outputs the values that mrank returns: /* * MRANKP.C * "Posix" C main program illustrating the use of the MATLAB Math * Library. * Calls mlfMrank, obtained by using MCC to compile mrank.m. * * $Revision: 1.3 $ * */ #include #include #include "matlab.h" /* Prototype for mlfMrank */ extern mxArray *mlfMrank( mxArray * ); main( int argc, char **argv ) { mxArray *N; /* Matrix containing n.
4 Stand-Alone Applications /* Print the results. */ mlfPrintMatrix(R); /* Free the matrices allocated during this computation. */ mxDestroyArray(N); mxDestroyArray(R); PkgTerminate(); /* Terminate the library of M-functions */ } An Explanation of mrankp.c The heart of mrankp.c is a call to the mlfMrank function. Most of what comes before this call is code that creates an input argument to mlfMrank. Most of what comes after this call is code that displays the vector that mlfMrank returns.
Mixing M-Files and C or C++ mlfPrintMatrix is one of the many routines in the MATLAB Math Built-In Library, which is part of the MATLAB Math Library. Finally, mrankp must free the heap memory allocated to hold matrices and call the Compiler-generated termination function: mxDestroyArray(N); mxDestroyArray(R); PkgTerminate();/* Terminate the library of M-functions */ Advanced C Example This section illustrates an advanced example of how to write C code that calls a compiled M-file.
4 Stand-Alone Applications mxArray *a, *b, *x, *y; double x_pr[ROWS * COLS] = {1, 2, 3, 4, double x_pi[ROWS * COLS] = {9, 2, 3, 4, double y_pr[ROWS * COLS] = {1, 2, 3, 4, double y_pi[ROWS * COLS] = {2, 9, 3, 4, double *a_pr, *a_pi, value_of_scalar_b; 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 1, 9}; 1}; 9}; 8}; multpkgInitialize();/* Call multpkg initialization */ /* Install a print handler to tell mlfPrintMatrix how to * display its output.
Mixing M-Files and C or C++ You can build this program into a stand-alone application by using the command mcc -t -W lib:multpkg -T link:exe multarg multargp.c libmmfile.mlib The program first displays the contents of a 3-by-3 matrix a and then displays the contents of scalar b: 6.2832 +34.5575i 12.5664 +34.5575i 18.8496 +18.8496i 25.1327 +25.1327i 31.4159 +31.4159i 37.6991 +37.6991i 43.9823 +43.9823i 50.2655 +28.2743i 56.5487 +28.2743i 143.
4 Stand-Alone Applications The mlfMultarg function returns matrices a and b. a has both real and imaginary components; b is a scalar having only a real component.
5 Controlling Code Generation This chapter describes the code generated by the MATLAB Compiler and the options that you can use to control code generation. Code Generation Overview (p. 5-2) Sample source files and generated filenames Compiling Private and Method Functions (p. 5-5) Working with private and method functions The Generated Header Files (p. 5-8) Generated C and C++ header files Internal Interface Functions (p. 5-11) Generated C and C++ interface functions Supported Executable Types (p.
5 Controlling Code Generation Code Generation Overview Example M-Files To generate the various files created by the Compiler, this chapter uses several different M-files — gasket.m, foo.m, fun.m, and sample.m. Sierpinski Gasket M-File function theImage = gasket(numPoints) %GASKET An image of a Sierpinski Gasket. % IM = GASKET(NUMPOINTS) % % Example: % x = gasket(50000); % imagesc(x);colormap([0 0 0;1 1 1]); % axis equal tight % % Copyright (c) 1984-98 by The MathWorks, Inc $Revision: 1.
Code Generation Overview b = y; end fun M-File function a = fun(b) a(1) = b(1) .* b(1); a(2) = b(1) + b(2); a(3) = b(2) / 4; sample M-File function y = sample( varargin ) varargin{:} y = 0; Generated Code This chapter investigates the generated header files, interface functions, and wrapper functions for the C MEX, stand-alone C and C++ targets, and C and C++ libraries.
5 Controlling Code Generation Table 5-1: Compiler-Generated Files C C++ Header file.h file.hpp Code file.c file.cpp Main Wrapper (-W main) file_main.c file_main.cpp MEX Wrapper (-W mex) file_mex.c N/A (C++ MEX-files are not supported.) Simulink Wrapper (-W simulink) file_simulink.c N/A (C++ MEX-files are not supported.) Library (-W lib:filelist) filelist.c filelist.h filelist.exports filelist.mlib filelist.cpp filelist.hpp filelist.mlib COM Component (-W com:compname[,classname[,major.
Compiling Private and Method Functions Compiling Private and Method Functions Private functions are functions that reside in subdirectories with the special name private, and are visible only to functions in the parent directory. Since private functions are invisible outside of the parent directory, they can use the same names as functions in other directories. Because MATLAB looks for private functions before standard M-file functions, it will find a private function before a nonprivate one.
5 Controlling Code Generation Name Description @cell/foo.m foo.m method to operate on cell arrays @cell/private/foo.m foo.m private to methods that operate on cell arrays This table lists the functions you can specify on the command line and their corresponding function and filenames. Function C Function C++ Function Filename foo mlfFoo mlxFoo mlNFoo mlfNFoo mlfVFoo foo Nfoo Vfoo mlxFoo foo.c foo.h foo.cpp foo.
Compiling Private and Method Functions Since it is ambiguous which foo.m you are requesting, it generates the warning Warning: The specified private directory is not unique. Both /Z/X/private and /Y/X/private are found on the path for this private directory.
5 Controlling Code Generation The Generated Header Files This section highlights the two header files that the Compiler can generate for the Sierpinski Gasket (gasket.m) example. C Header File If the target language is C, the Compiler generates the header file, gasket.h. This example uses the Compiler command mcc -t -L C -T codegen -F page-width:60 gasket to generate the associated files. The C header file, gasket.h, is /* * MATLAB Compiler: 3.
The Generated Header Files extern mxArray * mlfGasket(mxArray * numPoints); extern void mlxGasket(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[]); #ifdef __cplusplus } #endif #endif C++ Header File If the target language is C++, the Compiler generates the header file, gasket.hpp. This example uses the Compiler command mcc -t -L Cpp -T codegen -F page-width:60 gasket to generate the associated files. The C++ header file, gasket.hpp, is // // MATLAB Compiler: 3.
5 Controlling Code Generation extern mwArray gasket(mwArray numPoints = mwArray::DIN); #ifdef __cplusplus extern "C" #endif void mlxGasket(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[]); #endif 5-10
Internal Interface Functions Internal Interface Functions This section uses the Sierpinski Gasket example (gasket.m) to show several of the generated interface functions for the C and C++ cases. The remaining interface functions are generated by the example foo.m as described earlier in this chapter. Interface functions perform argument translation between the standard calling conventions and the Compiler-generated code.
5 Controlling Code Generation */ void mlxGasket(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[]) { mxArray * mprhs[1]; mxArray * mplhs[1]; int i; /* ------------- Input Argument Processing ------------ */ if (nlhs > 1) { mlfError( mxCreateString( "Run-time Error: File: gasket Line: 1 Column: " "1 The function \"gasket\" was called with mor" "e than the declared number of outputs (1).
Internal Interface Functions /* ------------- Output Argument Processing ----------- */ mlfRestorePreviousContext(0, 1, mprhs[0]); plhs[0] = mplhs[0]; } mlfF Interface Function The Compiler always generates the mlfF interface function, which contains the “normal” C interface to the function. This code is the corresponding C interface function (mlfGasket) from the Sierpinski Gasket example.
5 Controlling Code Generation This is the corresponding mlfNF interface function (mlfNFoo) for the foo.m example described earlier in this chapter. This function calls the Mfoo function that appears in foo.c: /* * The function "mlfNFoo" contains the nargout interface * for the "foo" M-function from file * "\extern\examples\compiler\foo.m" (lines 1-8). * This interface is only produced if the M-function uses * the special variable "nargout".
Internal Interface Functions mlfVF Interface Function The Compiler produces this interface function only when the M-function uses the variable nargout and has at least one output. This void interface function specifies zero output arguments to the implementation version of the function, and in the event that the implementation version still returns an output (which, in MATLAB, would be assigned to the ans variable), it deallocates the output.
5 Controlling Code Generation C++ Interface Functions The C++ interface functions process any input arguments and pass them to the implementation version of the function. Note In C++, the mlxF interface functions are also C functions in order to allow the feval interface to be uniform between C and C++. mlxF Interface Function The Compiler always generates the mlxF interface function, which is used by feval.
Internal Interface Functions int i; mclCppUndefineArrays(1, mplhs); if (nlhs > 1) { error( mwVarargin( mwArray( "Run-time Error: File: gasket Line:" " 1 Column: 1 The function \"gasket" "\" was called with more than the d" "eclared number of outputs (1)."))); } if (nrhs > 1) { error( mwVarargin( mwArray( "Run-time Error: File: gasket Line:" " 1 Column: 1 The function \"gasket" "\" was called with more than the d" "eclared number of inputs (1).
5 Controlling Code Generation // // The function "gasket" contains the normal interface for // the "gasket" M-function from file // "\extern\examples\compiler\gasket.m" (lines 1-23). // This function processes any input arguments and passes // them to the implementation version of the function, // appearing above.
Internal Interface Functions // function, appearing above.
5 Controlling Code Generation VF Interface Function The Compiler produces this interface function only when the M-function uses the variable nargout and has at least one output. The void interface function specifies zero output arguments to the implementation version of the function, and in the event that the implementation version still returns an output (which, in MATLAB, would be assigned to the ans variable), it deallocates the output.
Supported Executable Types Supported Executable Types Wrapper functions create a link between the Compiler-generated code and a supported executable type by providing the required interface that allows the code to operate in the desired execution environment. The wrapper functions differ depending on the execution environment, whereas the C and C++ header files and code that are generated by the Compiler are the same for MEX-functions, stand-alone applications, and libraries.
5 Controlling Code Generation MEX-Files The -W mex -L C options produce the MEX-file wrapper, which includes the mexFunction interface that is standard to all MATLAB plug-ins. For more information about the requirements of the mex interface, see External Interfaces/API in the MATLAB documentation. In addition to declaring globals and initializing the feval function table, the MEX-file wrapper function includes interface and definition functions for all M-files not included into the set of compiled files.
Supported Executable Types The Compiler processes the string arguments passed to the main() function and sends them into the compiled M-function as strings. For example, consider this M-file, sample.m. function y = sample( varargin ) varargin{:} y = 0; You can compile sample.m into a POSIX main application. If you call sample from MATLAB, you get sample hello world ans = hello ans = world ans = 0 If you compile sample.
5 Controlling Code Generation Simulink S-Functions The -W simulink -L C options produce a Simulink S-function wrapper. Simulink S-function wrappers conform to the Simulink C S-function conventions. The wrappers initialize • The sizes structure • The S-function’s sample times array • The S-function’s states and work vectors • The global variables and constant pool For more information about Simulink S-function requirements, see “Writing S-Functions” in the Simulink documentation.
Supported Executable Types This example uses several functions from the toolbox\matlab\timefun directory (weekday, date, tic, calendar, toc) to create a library wrapper. The -W lib:libtimefun -L C options produce the files shown in this table. File Description libtimefun.c C wrapper file libtimefun.h C header file libtimefun.exports C export list libtimefun.mlib M-file library libtimefun.c The C wrapper file (libtimefun.
5 Controlling Code Generation -B csharedlib:libtimefun with -t -W lib:libtimefun -T link:lib -h libmmfile.mlib giving the new statement mcc -t -W lib:libtimefun -T link:lib -h libmmfile.mlib weekday data tic calendar toc The -t option tells the Compiler to generate C code from each of the listed M-files. The -T link:lib option tells the Compiler to compile and link a shared library. The -h option tells the Compiler to include any other M-functions called from those listed on the mcc command line, i.e.
Supported Executable Types libtimefun.c libtimefun.h libtimefun.exports libtimefun.mlib libtimefun.ext The last file, libtimefun.ext, is the shared library file for your platform. For example, on the PC, the shared library is libtimefun.dll Using an mlib File. This example uses two functions, tic and toc, that are in the shared library.
5 Controlling Code Generation Note On the mcc command line, you can access any mlib file by including the full path to the file. For example: mcc -m timer /pathname/libtimefun.mlib Restrictions. • (UNIX) The first three characters of the filename must be lib. • (PC and UNIX) You cannot rename the file. • (PC and UNIX) Both the shared library and the mlib file must be in the same directory at compile time. • (PC and UNIX) At run time, the path to the shared library must be on the system’s search path.
Supported Executable Types This example uses several functions from the toolbox\matlab\timefun directory (weekday, date, tic, calendar, toc) to create a C++ library called libtimefun. The -W lib:libtimefun -L Cpp options produce the C++ library files shown in this table. File Description libtimefun.cpp C++ wrapper file libtimefun.hpp C++ header file Note On some platforms, including Microsoft Windows NT, support for C++ shared libraries is limited and the C++ mangled function names must be exported.
5 Controlling Code Generation The COM wrapper options create a superset of the files created when producing a C or C++ library wrapper. In addition to the C or C++ library files, the COM wrapper creates the files shown in the following table. File Description _idl.idl Interface description file for COM _com.hpp C++ header file for the COM class _com.cpp C++ source file for the COM class _dll.
Supported Executable Types When calling mbuild to link a library, the .dll file will be __.dll. This will prevent new versions from conflicting with each other. The user never uses the DLL name. It is not necessary to specify this name to the system because COM locates component DLLs using the Window’s registry. The MATLAB Compiler uses the -b option to generate a Visual Basic (.
5 Controlling Code Generation How mbuild Processes the File Types The mbuild option, -regsvr, uses the mwregsvr32 program to register the resulting shared library at the end of compilation. The Compiler uses this option whenever it produces a COM wrapper file. .idl. You can specify IDL source files on the mbuild command line. These files are compiled using the MIDL Compiler. The compiler adds any generated .idl files to the mbuild command line. .def.
Supported Executable Types C Signature. void mlxF(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]); mxArray *mlfNF( int mxArray mxArray . . mxArray mxArray . . ... ); nargout, ** y1, **y2, *x1, *x2, COM/IDL Signature. HRESULT f([in] long nargout, [in,out] VARIANT* Y1, [in,out] VARIANT* Y2, . . [in,out] VARIANT* varargout, [in] VARIANT X1, [in] VARIANT X2, . . [in] VARIANT varargin); The COM run-time performs all of the conversion between the COM types and MATLAB arrays.
5 Controlling Code Generation Porting Generated Code to a Different Platform The code generated by the MATLAB Compiler is portable among platforms. However, if you build an executable from foo.m on a PC running Windows, that same file will not run on a UNIX system. For example, you cannot simply copy foo.
Formatting Compiler-Generated Code Formatting Compiler-Generated Code The formatting options allow you to control the look of the Compiler-generated C or C++ code. These options let you set the width of the generated code and the indentation levels for statements and expressions. To control code formatting, use -F
5 Controlling Code Generation Default Width Not specifying a page width formatting option uses the default of 80.
Formatting Compiler-Generated Code NULL)); /* * * corners = [866 1;1 500;866 1000]; */ mclMline(15); mlfAssign( &corners, mlfDoubleMatrix( 3, 2, _array0_, (double *)NULL)); /* * startPoint = [866 1]; */ mclMline(16); mlfAssign( &startPoint, mlfDoubleMatrix( 1, 2, _array1_, (double *)NULL)); /* * theRand = rand(numPoints,1); */ mclMline(17); mlfAssign( &theRand, mlfNRand( 1, mclVa(numPoints, "numPoints"), mlfScalar(1), NULL)); . . .
5 Controlling Code Generation Default Indentation Not specifying indent formatting options uses the default of four spaces for statements and two spaces for expressions.
Formatting Compiler-Generated Code Modified Indentation This example shows the same segment of code using a statement indentation of two and an expression indentation of one: mcc -F statement-indent:2 -F expression-indent:1 -xg gasket generates the following code segment: 0 1 2 3 4 5 6 7 8 12345678901234567890123456789012345678901234567890123456789012345678901234567890 void mlxGasket(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[]) { mxArray * mprhs[1]; mxArray * mplhs[1]; int i; if (nlhs > 1) { ml
5 Controlling Code Generation Including M-File Information in Compiler Output The annotation options allow you to control the type of annotation in the Compiler-generated C or C++ code. These options let you include the comments and/or source code from the initial M-file(s) as well as #line preprocessor directives. You can also use an annotation option to generate source file and line number information when you receive run-time error messages.
Including M-File Information in Compiler Output Comments Annotation To include only comments from the source M-file in the generated output, use mcc -A annotation:comments This code snippet shows the generated code containing only the comments (“This is the hello ...”) in the middle of the routine: static void Mhello(void) { mclMlineEnterFunction("D:\\work\\hello.
5 Controlling Code Generation mxDestroyArray(ans); mclSetCurrentLocalFunctionTable(save_local_function_table_); mclMlineExitFunction(); } No Annotation To include no source from the initial M-file in the generated output, use mcc -A annotation:none This code snippet shows the generated code without comments and source code: static void Mhello(void) { mclMlineEnterFunction("D:\\work\\hello.
Including M-File Information in Compiler Output Note When using the #line directive, the page-width directive is disabled in order to make the code work properly with the C debugger. Include #line Directives To include #line directives in your generated C or C++ code, use mcc -A line:on The Hello, World example produces the following code segment when this option is selected. (Note that several lines have been truncated for readability.) #line 1 "D:\\work\\hello.
5 Controlling Code Generation Controlling Information in Run-Time Errors Use the debugline:setting option to include source filenames and line numbers in run-time error messages. The possible values for setting are • on • off Not specifying any debugline setting uses the default of off, which does not include filenames and line numbers in the generated run-time error messages. For example, given the M-file, tmmult.
Including M-File Information in Compiler Output your results are ??? Error using ==> tmmult Error using ==> * Inner matrix dimensions must agree. Error in File: "\extern\examples\compiler\tmmult.m", Function: "tmmult", Line: 4. Note When using the -A debugline:on option, the lasterr function returns a string that includes the line number information. If, in your M-code, you compare against the string value of lasterr, you will get different behavior when using this option.
5 Controlling Code Generation Interfacing M-Code to C/C++ Code The MATLAB Compiler supports calling arbitrary C/C++ functions from your M-code. You simply provide an M-function stub that determines how the code will behave in M, and then provide an implementation of the body of the function in C or C++. C Example Suppose you have a C function that reads data from a measurement device. In M-code, you want to simulate the device by providing a sine wave output.
Interfacing M-Code to C/C++ Code private, or method). When using this pragma, the Compiler will generate an additional header file called file_external.h or file_external.hpp, where file is the name of the initial M-file containing the %#external pragma. This header file will contain the extern declaration of the function that the user must provide. This function must conform to the same interface as the Compiler-generated code. The Compiler will still generate a .c or .cpp file from the .
5 Controlling Code Generation We recommend that you include this header file when defining the function. This function could be implemented in this C file, measure.c, using the measure_from_device() function. #include "matlab.h" #include "collect_external.h" #include extern double measure_from_device(void); mxArray * Mcollect_collect_one(int nargout_); { return( mlfScalar( measure_from_device() )); } double measure_from_device(void) { static double t = 0.0; t = t + 0.
Interfacing M-Code to C/C++ Code callback that references the specified function. Without this pragma, the -h option will not be able to locate and compile all M-files used in your application. If you are using the %#function pragma to define functions that are not available in M-code, you must write a dummy M-function that identifies the number of input and output parameters to the M-file function with the same name used on the %#function line.
5 Controlling Code Generation 5-50
6 Optimizing Performance The MATLAB Compiler can perform various optimizations on your M-file source code that can make the performance of the generated C/C++ code much faster than the performance of the M-code in the MATLAB interpreter. MATLAB Compiler 3.0 provides a series of optimizations that can help speed up your compiled code. This chapter describes the optimization options.
6 Optimizing Performance Optimization Bundles All optimizations are controlled separately, and you can enable or disable any of the optimizations. To simplify the process, you can use the provided bundles of Compiler settings that allow you to select the most common optimization options. For more information on bundles, see “-B :[,,...,] (Bundle of Compiler Settings)” on page 7-41.
Optimization Bundles • optimize_integer_for_loops • percolate_simple_types • speculate List All Optimizations To list all available optimizations, use -O list 6-3
6 Optimizing Performance Optimizing Arrays Scalar Arrays (fold_scalar_mxarrays) When this optimization is enabled, all constant, scalar-valued array operations are folded at compile time and are stored in a constant pool that is created once at program initialization time. Folding reduces the number of computations that are performed at run-time, thus improving run-time performance.
Optimizing Arrays If you compile this with the -O none option, you get ... mlfAssign( &y, mclMtimes( mlfDoubleMatrix(2, 2, _array0_, (double *)NULL), mlfDoubleMatrix(2, 2, _array1_, (double *)NULL))); ... Compiling with -O none -O fold_non_scalar_mxarrays:on gives ... mlfAssign(&y, _mxarray4_); ... Scalars (fold_mxarrays) This option is equivalent to using both fold_scalar_mxarrays and fold_non_scalar_mxarrays. It is included for compatibility with P-code generation.
6 Optimizing Performance Optimizing Loops Simple Indexing (array_indexing) This optimization improves the performance of simple oneand two-dimensional array index expressions. Without this optimization, all array indexing uses the fully general array indexing function, which is not optimized for one- and two-dimensional indexing. With this optimization enabled, indexing uses faster routines that are optimized for simple indexing.
Optimizing Loops Note This optimization causes the variable names in the resulting C program to differ from those in the M-file. Therefore, we recommend that you do not use this option when debugging. For example: function test(x) for i = 1:length(x)-1 x(i) = x(i) + x(i+1) end If you compile this with the -O none option, you get ... { mclForLoopIterator viter__; for (mclForStart( &viter__, mlfScalar(1), mclMinus(mlfLength(mclVa(x, "x")), mlfScalar(1)), NULL); mclForNext(&viter__, &i); ) { ...
6 Optimizing Performance for (; ; ) { ... if (v_ == e_) { break; } ++v_; } mlfAssign(&i, mlfScalar(v_)); } ...
Optimizing Conditionals Optimizing Conditionals (optimize_conditionals) This optimization reduces the MATLAB conditional operators to scalar C conditional operators when both operands are known to be integer scalars. The Compiler “knows” that nargin, nargout, and for-loop control variables (when using the above optimization) are integer scalars. For example: function test(a,b,c,d) if (nargin < 4) d = 0.0; end If you compile this with the -O none option, you get ...
6 Optimizing Performance Optimizing MATLAB Arrays Scalars (percolate_simple_types) This optimization reduces the strength of operations on simple types (scalars) by reducing operations to scalar double operations whenever possible. For example, if your code uses sin(v) and v is known to be double and scalar, this optimization uses the scalar double sin function. This optimization is always on when compiling to C/C++ and cannot be disabled. It is provided for compatibility with P-code generation.
7 Reference
7 Reference Functions — By Category Pragmas %#external Call arbitrary C/C++ functions. %#function feval pragma. %#mex Prefer the MEX-file over an existing M-file. Compiler Functions mbchar Impute char matrix. mbcharscalar Impute character scalar. mbcharvector Impute char vector. mbint Impute integer. mbintscalar Impute integer scalar. mbintvector Impute integer vector. mbreal Impute real. mbrealscalar Impute real scalar. mbrealvector Impute real vector. mbscalar Impute scalar.
Code Generation Options Control Compiler output. Optimization Options Improve the performance of the generated C/C++ code. Compiler and Control Compiler behavior. Environment Options mbuild/mex Options Control mbuild and mex.
7 Functions — By Name 7 %#external . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-5 %#function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6 %#mex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-7 mbchar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8 mbcharscalar .
%#external Purpose 7%#external Pragma to call arbitrary C/C++ functions from your M-code Syntax %#external Description The %#external pragma informs the Compiler that the implementation version of the function (Mf) will be hand written and will not be generated from the M-code. This pragma affects only the single function in which it appears, and any M-function may contain this pragma (local, global, private, or method).
%#function Purpose 7%#function feval pragma Syntax %#function Description This pragma informs the MATLAB Compiler that the specified function(s) will be called through an feval, eval, or Handle Graphics callback. You need to specify this pragma only to assist the Compiler in locating and automatically compiling the set of functions when using the -h option.
%#mex Purpose 7%#mex mex pragma Syntax %#mex Description This pragma informs the MATLAB Compiler to select the MEX-file over an existing M-file. If you are using the %#function pragma to define functions that are not available in M-code, you should use the %#external pragma to define the function.
mbchar Purpose 7mbchar Assert variable is a MATLAB character string Syntax mbchar(x) Description The statement mbchar(x) causes the MATLAB Compiler to impute that x is a char matrix. At run-time, if mbchar determines that x does not hold a char matrix, mbchar issues an error message and halts execution of the MEX-file. mbchar tells the MATLAB interpreter to check whether x holds a char matrix. If x does not, mbchar issues an error message and halts execution of the M-file.
mbcharscalar Purpose 7mbcharscalar Assert variable is a character scalar Syntax mbcharscalar(x) Description The statement mbcharscalar(x) causes the MATLAB Compiler to impute that x is a character scalar, i.e., an unsigned short variable. At run-time, if mbcharscalar determines that x holds a value other than a character scalar, mbcharscalar issues an error message and halts execution of the MEX-file. mbcharscalar tells the MATLAB interpreter to check whether x holds a character scalar value.
mbcharvector Purpose 7mbcharvector Assert variable is a character vector, i.e., a MATLAB string Syntax mbcharvector(x) Description The statement mbcharvector(x) causes the MATLAB Compiler to impute that x is a char vector. At run-time, if mbcharvector determines that x holds a value other than a char vector, mbcharvector issues an error message and halts execution of the MEX-file. mbcharvector tells the MATLAB interpreter to check whether x holds a char vector value.
mbint Purpose 7mbint Assert variable is integer Syntax mbint(n) Description The statement mbint(x) causes the MATLAB Compiler to impute that x is an integer. At run-time, if mbint determines that x holds a noninteger value, the generated code issues an error message and halts execution of the MEX-file. mbint tells the MATLAB interpreter to check whether x holds an integer value. If x does not, mbint issues an error message and halts execution of the M-file.
mbint x = 4 + 7.5i; Example This code in MATLAB causes mbint to generate an error message because n does not hold an integer value: n = 17.4; mbint(n); ??? Error using ==> mbint Argument to mbint must be integer.
mbintscalar Purpose 7mbintscalar Assert variable is integer scalar Syntax mbintscalar(n) Description The statement mbintscalar(x) causes the MATLAB Compiler to impute that x is an integer scalar. At run-time, if mbintscalar determines that x holds a value other than an integer scalar, mbintscalar issues an error message and halts execution of the MEX-file. mbintscalar tells the MATLAB interpreter to check whether x holds an integer scalar value.
mbintvector Purpose 7mbintvector Assert variable is integer vector Syntax mbintvector(n) Description The statement mbintvector(x) causes the MATLAB Compiler to impute that x is an integer vector. At run-time, if mbintvector determines that x holds a value other than an integer vector, mbintvector issues an error message and halts execution of the MEX-file. mbintvector tells the MATLAB interpreter to check whether x holds an integer vector value.
mbreal Purpose 7mbreal Assert variable is real Syntax mbreal(n) Description The statement mbreal(x) causes the MATLAB Compiler to impute that x is real (not complex). At run-time, if mbreal determines that x holds a complex value, mbreal issues an error message and halts execution of the MEX-file. mbreal tells the MATLAB interpreter to check whether x holds a real value. If x does not, mbreal issues an error message and halts execution of the M-file.
mbrealscalar Purpose 7mbrealscalar Assert variable is real scalar Syntax mbrealscalar(n) Description The statement mbrealscalar(x) causes the MATLAB Compiler to impute that x is a real scalar. At run-time, if mbrealscalar determines that x holds a value other than a real scalar, mbrealscalar issues an error message and halts execution of the MEX-file. mbrealscalar tells the MATLAB interpreter to check whether x holds a real scalar value.
mbrealvector Purpose 7mbrealvector Assert variable is a real vector Syntax mbrealvector(n) Description The statement mbrealvector(x) causes the MATLAB Compiler to impute that x is a real vector. At run-time, if mbrealvector determines that x holds a value other than a real vector, mbrealvector issues an error message and halts execution of the MEX-file. mbrealvector tells the MATLAB interpreter to check whether x holds a real vector value.
mbscalar Purpose 7mbscalar Assert variable is scalar Syntax mbscalar(n) Description The statement mbscalar(x) causes the MATLAB Compiler to impute that x is a scalar. At run-time, if mbscalar determines that x holds a nonscalar value, mbscalar issues an error message and halts execution of the MEX-file. mbscalar tells the MATLAB interpreter to check whether x holds a scalar value. If x does not, mbscalar issues an error message and halts execution of the M-file.
mbvector Purpose 7mbvector Assert variable is vector Syntax mbvector(n) Description The statement mbvector(x) causes the MATLAB Compiler to impute that x is a vector. At run-time, if mbvector determines that x holds a nonvector value, mbvector issues an error message and halts execution of the MEX-file. mbvector causes the MATLAB interpreter to check whether x holds a vector value. If x does not, mbvector issues an error message and halts execution of the M-file.
mbuild Purpose Syntax 7mbuild Compile and link source files that call functions in the MATLAB C/C++ Math Library or MATLAB C/C++ Graphics Library into a stand-alone executable or shared library mbuild [option1 ... optionN] sourcefile1 [... sourcefileN] [objectfile1 ... objectfileN] [libraryfile1 ... libraryfileN] [exportfile1 ... exportfileN] Note Supported types of source files are: .c, .cpp, .idl, .rc. To specify IDL source files to be compiled with the MIDL Compiler, add .
mbuild Table 7-1: mbuild Options (Continued) Option Description -D# Define a symbol name and value to the C/C++ preprocessor. Equivalent to a #define directive in the source. -D= (UNIX) Define a symbol name and value to the C preprocessor. Equivalent to a #define directive in the source. -f <> Specify location and name of options file to use. Overrides the mbuild default options file search mechanism.
mbuild Table 7-1: mbuild Options (Continued) 7-22 Option Description -lang Specify compiler language. can be c or cpp. By default, mbuild determines which compiler (C or C++) to use by inspection of the source file’s extension. This option overrides that mechanism. This option is necessary when you use an unsupported file extension, or when you pass in all .o files and libraries. -n No execute mode.
mbuild Table 7-1: mbuild Options (Continued) Option Description -regsvr (Windows) Use the regsvr32 program to register the resulting shared library at the end of compilation. The Compiler uses this option whenever it produces a COM wrapper file. -setup Interactively specify the compiler options file to use as default for future invocations of mbuild by placing it in \Application Data\MathWorks\ MATLAB\R13 (Windows) or $HOME/.matlab/R13 (UNIX).
mbuild Table 7-1: mbuild Options (Continued) Option Description = (UNIX) Override an options file variable for variable . If contains spaces, enclose it in single quotes, e.g., CFLAGS='opt1 opt2'. The definition, , can reference other variables defined in the options file. To reference a variable in the options file, prepend the variable name with a $, e.g., CFLAGS='$CFLAGS opt2'. # Override an options file variable for variable .
mcc Purpose 7mcc Invoke MATLAB Compiler Syntax mcc [-options] mfile1 Description mcc is the MATLAB command that invokes the MATLAB Compiler. You can issue the mcc command either from the MATLAB command prompt (MATLAB [mfile2 ... mfileN] [C/C++file1 ... C/C++fileN] mode) or the DOS or UNIX command line (stand-alone mode). Command Line Syntax You may specify one or more MATLAB Compiler option flags to mcc. Most option flags have a one-letter name.
mcc compilation, you can use one simple option, i.e., macro, that allows you to quickly accomplish basic compilation tasks. If you want to take advantage of the power of the Compiler, you can do whatever you desire to do by choosing various Compiler options. Table 7-2, Macro Options, shows the relationship between the macro approach to accomplish a standard compilation and the multioption alternative.
mcc Table 7-3, -m Macro, shows the options that compose the -m macro and the information that they provide to the Compiler. Table 7-3: -m Macro Option Function -t Translate M code to C/C++ code. -W main Produce a wrapper file suitable for a stand-alone application. -L C Generate C code as the target language. -T link:exe Create an executable as the output. -h Automatically, find and compile helper functions included in the source M-file. libmmfile.
mcc command line options. Both the mccstartup file and the -B option are processed the same way. Note If you need to change the meaning of a macro to satisfy your individual requirements, you should create or modify your mccstartup file in the preferences directory. Changing the file macro_option_x in the bundles directory changes the option for all Compiler users. To see the name of your preferences directory, type prefdir at the command prompt.
mcc Conflicting Options on Command Line If you use conflicting options, the Compiler resolves them from left to right, with the rightmost option taking precedence. For example, using the equivalencies in Table 7-2, Macro Options, mcc -m -W none test.m is equivalent to mcc -t -W main -L C -T link:exe -h -W none test.m In this example, there are two conflicting -W options.
mcc mcc -m -I /home/user/dir1 -I /home/user/dir2 myfile.m The Compiler finds the myfile.m in dir1 and compiles it instead of the one in dir2 because of the behavior of the -I option. If you are concerned that this might be happening, you can specify the -v option and then see which M-file the Compiler parses. The -v option prints the full pathname to the M-file.
mcc MATLAB Compiler Option Flags The MATLAB Compiler option flags perform various functions that affect the generated code and how the Compiler behaves. Table 7-4, Compiler Option Categories, shows the categories of options. Table 7-4: Compiler Option Categories Category Purpose Macros The macro options simplify the compilation process by combining the most common compilation tasks into single options. Code Generation These options affect the actual code that the Compiler generates.
mcc In addition to the -G option, the -g option includes the -A debugline:on option. This will have an impact on performance of the generated code. If you want to have debugging information, but do not want the performance degradation associated with the debug line information, use -g -A debugline:off. The -g option also includes the -O none option, causing all compiler optimizations to be turned off. If you want to have some optimizations on, you may specify them after the debug option.
mcc -S (Simulink S-Function). Produce a Simulink S-function that is compatible with the Simulink S-Function block. For example, to translate an M-file named mymfile.m into C and to create the corresponding Simulink S-function using dynamically sized inputs and outputs, use mcc -S mymfile The -S option is equivalent to the series of options -W simulink -L C -t -T link:mex libmatlbmx.mlib or -B macro_option_s -x (MEX-Function). Produce a MEX-function. For example, to translate an M-file named mymfile.
mcc -B sgl -t -W comhg:,, -T link:lib -h libmmfile.mlib -i -B csglexcel (C Handle Graphics Excel COM Object). Produce a C Excel COM object that uses Handle Graphics. The -B csglexcel option is equivalent to the series of options -B sgl -t -W excelhg:,, -T link:lib -h libmmfile.mlib -b -i -B csglsharedlib (C Handle Graphics Shared Library). Produce a C shared library that uses Handle Graphics.
mcc -B csharedlib (C Shared Library). Produce a C shared library. The -B csharedlib option is equivalent to the series of options -t -W lib: -T link:lib -h libmmfile.mlib -B pcode (MATLAB P-Code). Produce MATLAB P-code. The -B pcode option is equivalent to the series of options -t -L P -B sgl (Stand-Alone C Graphics Library). Produce a stand-alone C application that uses Handle Graphics. The -B sgl option is equivalent to the series of options -m -W mainhg libmwsglm.
mcc Table 7-5, Code/Comment Annotation Options, shows the available annotation options. Table 7-5: Code/Comment Annotation Options Type Description all Provides the complete source of the M-file interleaved with the generated C/C++ source. The default is all. comments Provides all of the comments from the M-file interleaved with the generated C/C++ source. none No comments or code from the M-file are added to code.
mcc Table 7-7, Run-Time Error Annotation Options, shows the available debugline directive settings. Table 7-7: Run-Time Error Annotation Options Setting Description on Specifies the presence of source file and line number information in run-time error messages. off Specifies no source file and line number information in run-time error messages. The default is off.
mcc Table 7-8: Formatting Options (Continued)
mcc Table 7-9: Optimization Options (Continued)
mcc Table 7-10: Function Wrapper Types (Continued) Description lib: Produces an initialization and termination function for use when compiling this Compiler-generated code into a larger application. This option also produces a header file containing prototypes for all public functions in all M-files specified. becomes the base (file) name for the generated C/C++ and header file. Creates a .exports file that contains all nonstatic function names.
mcc -y (Number of Outputs). Provide more control over the number of valid outputs for your Simulink S-function. This option specifically sets the number of outputs (y) for your function. If -y is omitted, the output will be dynamically sized. (Use this with the -S option.) Compiler and Environment Options -b (Visual Basic File). Generate a Visual Basic file (.bas) that contains the Microsoft Excel Formula Function interface to the Compiler-generated COM object.
mcc Note You can use the -B option with a replacement expression as is at the DOS or UNIX prompt. To use -B with a replacement expression at the MATLAB prompt, you must enclose the expression that follows the -B in single quotation marks. For example: >>mcc -B 'csharedlib:libtimefun' weekday data tic calendar toc This table shows the available bundle files. Bundle File Name Contents ccom -t -W com:,, -T link:lib -h libmmfile.
mcc Bundle File Name Contents macro_option_m -W main -L C -t -T link:exe -h libmmfile.mlib macro_option_p -W main -L cpp -t -T link:exe -h libmmfile.mlib macro_option_S -W simulink -L C -t -T link:mex libmatlbmx.mlib macro_option_x -W mex -L C -t -T link:mexlibrary libmatlbmx.
mcc The -h option purposely does not include built-in functions or functions that appear in the MATLAB M-File Math Library portion of the C/C++ Math Libraries. This prevents compiling functions that are already part of the C/C++ Math Libraries. If you want to compile these functions as helper functions, you should specify them explicitly on the command line. For example, use mcc -m minimize_it fminsearch instead of mcc -m -h minimize_it -i (Include Exported Interfaces).
mcc Table 7-11: Output Stage Options Description codegen Translates M-files to C/C++ files and generates a wrapper file. The default is codegen. compile:mex Same as codegen plus compiles C/C++ files to object form suitable for linking into a Simulink S-function MEX-file. compile:mexlibrary Same as codegen plus compiles C/C++ files to object form suitable for linking into an ordinary (non-S-function) MEX-file.
mcc -v (Verbose). Display the steps in compilation, including • The Compiler version number • The source filenames as they are processed • The names of the generated output files as they are created • The invocation of mex or mbuild The -v option passes the -v option to mex or mbuild and displays information about mex or mbuild. -w (Warning). Display warning messages. Table 7-12, Warning Option, shows the various ways you can use the -w option.
mcc Table 7-12: Warning Option (Continued) Syntax Description -w enable[:] Enables specific warning associated with . Appendix B, “Error and Warning Messages” lists the valid values. Leave off the optional : to apply the enable action to all warnings. -w error[:] Treats specific warning associated with as error. Leave off the optional : to apply the error action to all warnings. -Y . Use license information in license.
mcc Note Multiple -M options do not accumulate; only the last -M option is used. -z (Specifying Library Paths). Specify the path to use for library and include files. This option uses the specified path for compiler libraries instead of the path returned by matlabroot. Examples Make a C translation and a MEX-file for myfun.m: mcc -x myfun Make a C translation and a stand-alone executable for myfun.m: mcc -m myfun Make a C++ translation and a stand-alone executable for myfun.
mcc mcc -t -L C myfun Make a generic C++ translation of myfun.m: mcc -t -L Cpp myfun Make a C MEX wrapper file from myfun1.m and myfun2.m: mcc -W mex -L C myfun1 myfun2 Make a C translation and a stand-alone executable from myfun1.m and myfun2.m (using one mcc call): mcc -m myfun1 myfun2 Make a C translation and a stand-alone executable from myfun1.m and myfun2.m (by generating each output file with a separate mcc call): mcc mcc mcc mcc mcc mcc mcc -t -t -W -T -T -T -T -L C myfun1 % Yields myfun1.
mcc 7-50
A MATLAB Compiler Quick Reference This appendix summarizes the Compiler options and provides brief descriptions of how to perform common tasks. Common Uses of the Compiler (p. A-2) Brief summary of how to use the Compiler mcc (p.
A MATLAB Compiler Quick Reference Common Uses of the Compiler This section summarizes how to use the MATLAB Compiler to generate some of its more standard results. The first four examples take advantage of the macro options. Create a MEX-File. To translate an M-file named mymfile.m into C and to create the corresponding C MEX-file that can be called directly from MATLAB, use mcc -x mymfile Create a Simulink S-Function. To translate an M-file named mymfile.
Common Uses of the Compiler Create a C++ Library. To create a C++ library, use mcc -p -W lib:libfoo -T compile:lib foo.m Create a C Shared Library. To create a C shared library that performs specialized calculations that you can call from your own programs, use mcc -W lib:mylib -L C -t -T link:lib -h Function1 Function2 Create MATLAB P-Code. To translate an M-file named mymfile.m into MATLAB P-code, use mcc -B pcode mymfile Note You can add the -g option to any of these for debugging purposes.
A MATLAB Compiler Quick Reference mcc Bold entries in the Comment/Options column indicate default values.
mcc Table A-1: mcc Quick Reference (Continued) Option Description Comment/Options F option Specifies format parameters option = g Generates debugging information Equivalent to G Debug only. Simply turn debugging on, so debugging symbol information is included. h Compiles helper functions i Causes Compiler to include only M-files specified on the command line as exported interfaces.
A MATLAB Compiler Quick Reference Table A-1: mcc Quick Reference (Continued) Option Description Comment/Options O O O O Build an optimized executable.
mcc Table A-1: mcc Quick Reference (Continued) Option Description Comment/Options w option Displays warning messages option = list level level:string where level = disable enable error No w option displays only serious warnings (default). W type Controls the generation of function wrappers type = mex main simulink lib:string com:compnm[,clnm[,mj.mn]] comhg:compnm[,clnm[,mj.mn]] excel:compnm[,clnm[,mj.mn]] excelhg:compnm[,clnm[,mj.
A MATLAB Compiler Quick Reference A-8
B Error and Warning Messages This appendix lists and describes error messages and warnings generated by the MATLAB Compiler. Compile-time messages are generated during the compile or link phase. It is useful to note that most of these compile-time error messages should not occur if MATLAB can successfully execute the corresponding M-file. Run-time messages are generated when the executable program runs.
B Error and Warning Messages Compile-Time Errors Error: An error occurred while shelling out to mex/mbuild (error code = errorno). Unable to build executable (specify the -v option for more information). The Compiler reports this error if mbuild or mex generates an error. Error: An error occurred writing to file "filename": reason. The file could not be written. The reason is provided by the operating system. For example, you may not have sufficient disk space available to write the file.
Compile-Time Errors Error: File: filename Line: # Column: # () indexing must appear last in an index expression. If you use ordinary array indexing () to index into an expression, it must be last in the index expression. For example, you can use X(1).value and X{2}(1), but you cannot use X.value(1) or X(1){2}. Error: File: filename Line: # Column: # A CONTINUE may only be used within a FOR or WHILE loop. Use Continue to pass control to the next iteration of a for or while loop.
B Error and Warning Messages Error: File: filename Line: # Column: # An array for multiple LHS assignment cannot contain token. If the left-hand side of a statement is a multiple assignment, the vector cannot contain this token. For example, you cannot assign to constants. [p1] = myfunc(a) [3] = myfunc(a) % Correct % Incorrect Error: File: filename Line: # Column: # Expected a variable, function, or constant, found "string". There is a syntax error in the specified line.
Compile-Time Errors Error: File: filename Line: # Column: # Missing variable or function. An illegal name was used for a variable or function. For example: x _x % Correct % Incorrect Error: File: filename Line: # Column: # Only functions can return multiple values. In this example, foo must be a function, it cannot be a variable. [a, b] = foo; Error: File: filename Line: # Column: # "string1" expected, "string2" found. There is a syntax error in the specified line.
B Error and Warning Messages Error: File: filename Line: # Column: # The PERSISTENT declaration must precede any use of the variable variablename. In the text of the function, there is a reference to the variable before the persistent declaration. Error: File: filename Line: # Column: # The single colon operator (:) can only be used within an array index expression. You can only use the : operator by itself as an array index. For example: A(:) = 5; is okay, but y = :; is not.
Compile-Time Errors Error: Found illegal whitespace character in command line option: "string". The strings on the left and right side of the space should be separate arguments to MCC. For example: mcc('-A', 'none') mcc('-A none') % Correct % Incorrect Error: Improper usage of option -optionname. Type "mcc -?" for usage information. You have incorrectly used a Compiler option.
B Error and Warning Messages Error: The argument after the -option option must contain a colon. The format for this argument requires a colon. For more information, see “MATLAB Compiler Option Flags” on page 7-31 or type mcc -? at the command prompt. Error: The environment variable MATLAB must be set to the MATLAB root directory. On UNIX, the MATLAB and LM_LICENSE_FILE variables must be set. The mcc shell script does this automatically when it is called the first time.
Compile-Time Errors Error: The specified file "filename" cannot be read. There is a problem with your specified file. For example, the file is not readable because there is no read permission. Error: The -option option cannot be combined with other options. The -V2.0 option must appear separate from other options on the command line. For example: mcc -V2.0 -L Cpp mcc -V2.0L Cpp % Correct % Incorrect Error: The -optionname option requires an argument (e.g. "proper_example_usage").
B Error and Warning Messages Error: Unknown annotation option: optionname. An invalid string was specified after the -A option. For a complete list of the valid annotation options, see “MATLAB Compiler Option Flags” on page 7-31 or type mcc -? at the command prompt. Error: Unknown typesetting option: optionname. The valid typesetting options available with -F are expression-indent:n, list, page-width, and statement-indent:n. Error: Unknown warning enable/disable string: warningstring.
Warning Messages Warning Messages This section lists the warning messages that the MATLAB Compiler can generate. Using the -w option for mcc, you can control which messages are displayed. Each warning message contains a description and the warning message identifier string (in parentheses) that you can enable or disable with the -w option.
B Error and Warning Messages Warning: File: filename Line: # Column: # The call to function "functionname" on this line could not be bound to a function that is known at compile time. A run-time error will occur if this code is executed. (no_matching_function) The called function was not found on the search path. Warning: File: filename Line: # Column: # Attempt to clear value when it has not been previously defined.
Warning Messages will be called through an feval call. This is used so that the -h option will automatically compile the selected functions. Warning: File: filename Line: # Column: # The call to function "functionname" on this line passed quantity1 inputs and the function is declared with quantity2. A run-time error will occur if this code is executed. (too_many_inputs) There is an inconsistency between the number of formal and actual inputs to the function.
B Error and Warning Messages Warning: File: filename Line: # Column: # The load statement cannot be translated unless it specifically lists the names of variables to be loaded as constant strings.
Warning Messages Warning: File: filename Line: # Column: # The second output argument from the "functionname" function is only available in MEX mode. A run-time error will occur if this code is executed in stand-alone mode. (unix_dos_second_argument) The DOS command can be called with two output arguments. That form cannot be compiled in stand-alone mode. This warning occurs if the DOS command was called with two output arguments in a file that is being compiled in stand-alone mode.
B Error and Warning Messages Warning: M-file "filename" was specified on the command line with full path of "pathname", but was found on the search path in directory "directoryname" first. (specified_file_mismatch) The Compiler detected an inconsistency between the location of the M-file as given on the command line and in the search path. The Compiler uses the location in the search path.
Warning Messages Warning: The name of a shared library should begin with the letters "lib". "libraryname" doesn’t. (missing_lib_sentinel) This warning is generated if the name of the specified library does not begin with the letters “lib”. This warning is specific to UNIX and does not occur on Windows. For example: mcc -t -W lib:liba -T link:lib a0 a1 % No warning mcc -t -W lib:a -T link:lib a0 a1 % Will generate a warning Warning: The option optionname is ignored in modename mode (specify -? for help).
B Error and Warning Messages Run-Time Errors Note The error messages described in this section are generated by the Compiler into the code exactly as they are written, but are not the only source of run-time errors. You also can receive run-time errors can from the C/C++ Math Libraries; these errors are not documented in this book. Math Library errors do not include the source file and line number information.
Run-Time Errors Run-time Error: File: filename Line: # Column: # The function "functionname" was called with more than the declared number of outputs (quantity1). There is an inconsistency between the declared number of formal outputs and the actual number of outputs. Run-time Error: File: filename Line: # Column: # The load statement did not specifically list the names of variables to be loaded as constant strings.
B Error and Warning Messages B-20
Index Symbols #line directives 5-42 -B cppexcel option flag 7-34 %#external 7-5 -B cpplib option flag 7-34 %#function 7-6 -B cppsglcom option flag 7-34 %#mex 7-7 -B cppsglexcel option flag 7-34 %#mex pragma 7-7 -B csglcom option flag 7-33 .cshrc 4-11 -B csglexcel option flag 7-34 .
Index C++ compilers supported on PCs 2-14 supported on UNIX 2-4 interfacing to M-code 5-46 library wrapper 5-28 required features templates 4-6 callback problems, fixing 1-20 callback strings searching M-files for 1-21 changing compiler on PC 2-20 changing license file -Y option flag 7-47 code controlling #line directives 5-42 controlling comments in 5-40 controlling run-time error information 5-44 hiding 1-16 porting 5-34 setting indentation 5-35 setting width 5-35 COM component wrapper 5-29 COM object bu
Index duality command/function 5-22 E embedded M-file 7-30 environment variable 2-26 library path 4-11 out of environment space on Windows 2-25 error messages Compiler B-1 compile-time B-2–B-10 internal error B-1 run-time B-18–B-19 warnings B-11–B-17 errors getting line numbers of 7-38 Excel plug-in building 4-32 executables. See wrapper file.
Index G -G option flag 7-47 -g option flag 7-31 gasket.
Index limitations of MATLAB Compiler 2.0 1-18 built-in functions 1-18 exist 1-18 objects 1-18 script M-file 1-18 #line directives 5-42 line numbers 7-38 Linux 2-4 locating shared libraries on UNIX 4-11 M -M option flag 7-47 -m option flag 4-37, 7-32 macro option 3-6 -B pcode 7-35 -B sgl 7-35 -B sglcpp 7-35 -m 7-32 -p 7-32 -S 7-33 -x 7-33 main program 5-22 main wrapper 5-22 main.
Index MATLAB libraries M-file Math 4-40, 7-44 MATLAB plug-ins. See MEX wrapper.
Index M-file compiling embedded 7-30 example gasket.m 3-2 houdini.m 3-10 main.m 4-36 mrank.m 4-36, 4-42 function 3-10 MATLAB-provided 4-40 script 1-18, 3-10 M-files searching for callback strings 1-21 mglinstaller 4-27 mglinstaller.
Index options file combining customized on PC 4-21 locating 2-16 locating on PC 4-16 locating on UNIX 4-8 making changes persist on PC 4-20 UNIX 4-10 modifying on PC 2-21, 4-19 UNIX 4-10 PC 2-16 purpose 4-6 temporarily changing on PC 4-21 UNIX 4-10 UNIX 2-6 out of environment space on Windows 2-25 outputs dynamically sized 3-7 setting number 3-8 PC options file 2-16 running stand-alone application 4-22 supported compilers 2-14 PC compiler limitations 2-15 percolate_simple_types optimization 6-10 personal
Index scalar arrays folding 6-4 script M-file 1-18, 3-10 converting to function M-files 3-10 setting default options 7-27 S-function 3-7 generating 3-7 passing inputs 3-7 passing outputs 3-7 shared library 1-16, 4-30 distributing with stand-alone application 4-5 header file 5-24 locating on PC 4-22 locating on UNIX 4-11 UNIX 4-11 wrapper 5-24 SHLIB_PATH run-time libraries 4-28 Sierpinski Gasket 5-2 Simulink compatible code 3-7 S-function 3-7 -u option flag 7-39 wrapper 5-24 -y option flag 7-41 Simulink S-
Index templates requirement 4-6 translate M to C -t option flag 7-44 troubleshooting Compiler problems 2-27, 4-35 mbuild problems 4-33 MEX-file problems 2-25 missing functions 1-20 starting stand-alone graphics applications 4-28 U -u option flag 3-8, 7-39 uicontrol objects 1-21 uimenu objects 1-21 UNIX building stand-alone applications 4-7 Compiler installation 2-4 options file 2-6 running stand-alone application 4-12 supported compilers 2-4 system requirements 2-4 UNIX compiler limitations 2-5 unsupport