MATLAB Compiler The Language of Technical Computing Computation Visualization Programming User’s Guide Version 2.
How to Contact The MathWorks: 508-647-7000 Phone 508-647-7001 Fax The MathWorks, Inc. 3 Apple Hill Drive Natick, MA 01760-2098 Mail http://www.mathworks.com Web Anonymous FTP server Newsgroup ftp.mathworks.com comp.soft-sys.matlab support@mathworks.com suggest@mathworks.com bugs@mathworks.com doc@mathworks.com subscribe@mathworks.com service@mathworks.com info@mathworks.
Contents Introducing the MATLAB Compiler 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Before You Begin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . New Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Compiler Licensing Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 1-2 1-3 1-5 Uses of the Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
UNIX Workstation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5 System Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7 mex Verification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8 MATLAB Compiler Verification . . . . . . . . . . . . . . . . . . . . . . . . 2-12 Microsoft Windows on PCs . . . . . . . . . . .
Stand-Alone Applications 4 Differences Between MEX-Files and Stand-Alone Applications . . . . . . . . . . . . . . . . . . . . . . . . . 4-3 Stand-Alone C Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3 Stand-Alone C++ Applications . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4 Building Stand-Alone C/C++ Applications . . . . . . . . . . . . . . . 4-5 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5 Getting Started . . .
Mixing M-Files and C or C++ . . . . . . . . . . . . . . . . . . . . . . . . . . 4-37 Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-37 Advanced C Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-42 Controlling Code Generation 5 Code Generation Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3 Example M-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3 Generated Code . . . . . . . . .
Including M-File Information in Compiler Output . . . . . . Controlling Comments in Output Code . . . . . . . . . . . . . . . . . . Controlling #line Directives in Output Code . . . . . . . . . . . . . . Controlling Information in Run-Time Errors . . . . . . . . . . . . . . 5-34 5-34 5-36 5-38 Interfacing M-Code to C/C++ Code . . . . . . . . . . . . . . . . . . . . . 5-40 C Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-40 Using Pragmas . . . . . . . . . . . .
Reference 7 Pragmas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . %#external . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . %#function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . %#mex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4 7-5 7-6 7-7 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Error and Warning Messages B Compile-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-3 Warning Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-12 Run-Time Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
viii Contents
1 Introducing the MATLAB Compiler Introduction . . . . . . Before You Begin . . . . . New Features . . . . . . Compiler Licensing Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 1-2 1-3 1-5 Uses of the Compiler . . . . . . . . . . . . . . . . 1-7 Creating MEX-Files . . . . . . . . . . . . . . . . . 1-7 Creating Stand-Alone Applications . . . . . . . . . . . 1-9 The MATLAB Compiler Family . . . . . . . . . . .
1 Introducing the MATLAB Compiler Introduction This book describes version 2.1 of the MATLAB® Compiler. The MATLAB Compiler takes M-files as input and generates C or C++ source code or P-code as output. The MATLAB Compiler can generate these kinds of source code: • C source code for building MEX-files. • C or C++ source code for combining with other modules to form stand-alone applications.
New Features MATLAB Compiler 2.1 supports much of the functionality of MATLAB 6. The new features of the Compiler are: • Optimizations • mlib files • Additional data type support • Improved support for load and save • Dynamically linking in MEX-files in the stand-alone environment • MATLAB add-in for Visual Studio • Faster C/C++ Math Library applications • Additional language support Note The MATLAB Compiler 2.
1 Introducing the MATLAB Compiler mlib Files mlib files make it possible to produce a shared library out of a toolbox and then compile M-files that make calls into that toolbox. Specifying an mlib file tells the MATLAB Compiler to link against the mlib file’s corresponding shared library whenever it needs to use any of the functions found in that library. The mlib file and its corresponding shared library file must be located within the same directory.
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.2 option is no longer supported, along with any options recognized by Compiler 1.2. Compiler Licensing Changes Starting with Compiler 1.2.
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 • Shadowed blocks are MathWorks tools. • Unshaded blocks are MATLAB Compiler-generated code. mex • 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 C Compiler • Shadowed blocks are tools. • Unshaded blocks are MATLAB Compiler-generated code. • Dotted blocks are C/C++ compiler-generated executables.
Uses of the Compiler See “Stand-Alone Applications” for complete details regarding stand-alone applications. Figure 1-2 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, a C++ compiler instead of a C compiler, and the MATLAB C/C++ Math Library. Note The MATLAB Compiler contains a tool, mbuild, which simplifies much of this process.
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 one of four wrapper files depending on your specified target. This table shows the wrapper files the Compiler can generate, their associated targets, and the corresponding -W option (wrapper). Table 1-1: Compiler 2.
1 Introducing the MATLAB Compiler Why Compile M-Files? There are three main reasons to compile M-files: • To create stand-alone applications or C shared libraries (DLLs on Windows) or C++ static libraries • To hide proprietary algorithms • To speed them up 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.
Why Compile M-Files? Cases When Performance Does Not Improve. Compilation is not likely to speed up M-file functions that: • Are heavily vectorized • Spend most of their time in MATLAB’s built-in indexing, math, or graphics functions Cases When Performance Does Improve. Compilation is most likely to speed up M-file functions that contain loops.
1 Introducing the MATLAB Compiler Upgrading from Previous Versions MATLAB Compiler 2.0 The MATLAB Compiler 2.1 does not support the -V1.2 option that was available in Compiler 2.0. MATLAB Compiler 1.2 Compatibility The MATLAB Compiler 2.1 is fully compatible with previous releases of the Compiler. If you have 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.
Limitations and Restrictions Limitations and Restrictions MATLAB Code This version of the MATLAB Compiler supports almost all of the functionality of MATLAB. However, there are some limitations and restrictions that you should be aware of. Although this version of the MATLAB Compiler cannot compile the following, a future version will be able to compile them: • Script M-files (See “Converting Script M-Files to Function M-Files” in Chapter 3 for further details.
1 Introducing the MATLAB Compiler Stand-Alone Applications The restrictions and limitations noted in the previous section also apply to stand-alone applications. The functions in this table are supported in MEX-mode, but are not supported in stand-alone mode. Note You cannot call any Handle Graphics functions unless you have the optional Graphics Library installed. In addition, stand-alone applications cannot access Simulink functions.
Limitations and Restrictions Table 1-2: Unsupported Functions in Stand-Alone Mode (Continued) rehash runtime set_param sim simget simset sldebug str2func superiorto system_dependent trmginput type vms what which who whos 1-19
1 Introducing the MATLAB Compiler 1-20
2 Installation and Configuration System Configuration for MEX-Files . . . . . . . . . 2-3 UNIX Workstation . . . . System Requirements . . . . Installation . . . . . . . . mex Verification . . . . . . MATLAB Compiler Verification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5 2-5 2-7 2-8 2-12 Microsoft Windows on PCs System Requirements . . . . Installation . . . . . . . . mex Verification . . . . . .
2 Installation and Configuration This chapter explains: • The system requirements you need to use the MATLAB Compiler • How to install the MATLAB Compiler • How to configure the MATLAB Compiler after you have installed it This chapter includes information for both MATLAB Compiler platforms — UNIX and Microsoft Windows. For information about the MATLAB Compiler not available at print time, see the MATLAB Compiler 2.1 Release Notes.
System Configuration for MEX-Files 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. 3 Verify that mex can generate MEX-files.
2 Installation and Configuration 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.
UNIX Workstation UNIX Workstation This section examines the system requirements, installation procedures, and configuration procedures for the MATLAB Compiler on UNIX systems. System Requirements You cannot install the MATLAB Compiler unless MATLAB 6/Release 12 is already installed on the system. The MATLAB Compiler imposes no operating system or memory requirements beyond those that are necessary to run MATLAB. The MATLAB Compiler consumes a small amount of disk space.
2 Installation and Configuration Note Although the MATLAB Compiler supports the creation of stand-alone C++ applications, it does not support the creation of C++ MEX-files. Supported ANSI C and C++ UNIX Compilers The MATLAB Compiler supports: • The GNU C compiler, gcc, (except on HP and SGI64) • The system’s native ANSI C compiler on all UNIX platforms • The system’s native C++ compiler on all UNIX platforms (except Linux) • The GNU C++ compiler, g++, on Linux.
UNIX Workstation 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.
2 Installation and Configuration 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.
UNIX Workstation If you do not need to change C or C++ compilers, or you do not need to modify your compiler options files, you can skip ahead in this section to “Creating MEX-Files” on page 2-10. If you need to know how to change the options file, continue with this section. Changing Compilers Changing the Default Compiler. To change your default C or C++ compiler, you select a different options file.
2 Installation and Configuration 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).
UNIX Workstation On UNIX, MEX-files are created with platform-specific extensions, as shown in this table. Table 2-2: MEX-File Extensions for UNIX Platform MEX-File Extension DEC 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.
2 Installation and Configuration 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.
UNIX Workstation 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.mexsol.
2 Installation and Configuration Microsoft Windows on PCs This section examines the system requirements, installation procedures, and configuration procedures for the MATLAB Compiler on PCs running Windows 95/98/2000 or Windows NT. System Requirements You cannot install the MATLAB Compiler unless MATLAB 6/Release 12 is already installed on the system. The MATLAB Compiler imposes no operating system or memory requirements beyond what is necessary to run MATLAB.
Microsoft Windows on PCs Note Although the MATLAB Compiler supports the creation of stand-alone C++ applications, it does not support the creation of C++ MEX-files. 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.
2 Installation and Configuration • The MATLAB Compiler 2.1 sometimes will generate goto statements for complicated if conditions. The Borland C++ Compiler prohibits the goto statement within a try…catch block. This error can occur if you use the -A debugline:on option, because its implementation uses try…catch. To work around this limitation, simplify the if conditions. • There is a limitation with the Borland C++ Compiler.
Microsoft Windows on PCs 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 C/C++, Version 5.0 Microsoft C/C++, Version 6.0 msvc50opts.bat msvc60opts.bat Watcom C/C++, Version 10.6 Watcom C/C++, Version 11.
2 Installation and Configuration created during the -setup process, in a subdirectory of your user profile directory, named Application Data\MathWorks\MATLAB\R12. Under Windows NT and Windows 95/98/2000 with user profiles enabled, your user profile directory is %windir%\Profiles\username. Under Windows 95/98/2000 with user profiles disabled, your user profile directory is %windir%. Under Windows 95/98/2000, you can determine whether or not user profiles are enabled by using the Passwords control panel.
Microsoft Windows on PCs Things to Be Aware of This table provides information regarding the installation and configuration of a C/C++ compiler on your system. Description Comment 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.
2 Installation and Configuration mex Verification Choosing a Compiler Systems with Exactly One C/C++ Compiler. If you have properly installed the MATLAB Compiler and your supported C or C++ compiler, you can now create C MEX-files. On systems where there is exactly one C or C++ compiler available to you, the mex utility automatically configures itself for the appropriate compiler. So, for many users, to create a C MEX-file, you can simply enter mex filename.
Microsoft Windows on PCs [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.
2 Installation and Configuration [0] None Compiler: 11 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\R12\mexopts.bat" is being updated...
Microsoft Windows on PCs copy of the options file in your user profile directory to correspond to your specific needs and save the modified file. After completing this process, the mex script will use the new options file everytime with your modified settings. Temporarily Changing the Compiler. To temporarily change your C or C++ compiler, use the -f option, as in mex -f … The -f option tells the mex script to use the options file, .
2 Installation and Configuration information about the add-in, see “Using an IDE” in Chapter 4, “Stand-Alone Applications.” 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.
Microsoft Windows on PCs Copy invhilb.m from the \toolbox\matlab\elmat directory to a local directory and then type the following at the DOS prompt. mcc -x invhilb Next, verify that invhilb is now a MEX-file by listing the invhilb files. dir invhilb* You will see a list containing invhilb.c invhilb.dll invhilb.h invhilb.m invhilb_mex.c These are the files that the Compiler generates from the M-file, in addition to the original M-file, invhilb.m.
2 Installation and Configuration Troubleshooting This section identifies some of the more common problems that can occur when installing and configuring the MATLAB Compiler. mex Troubleshooting Out of Environment Space Running mex or mbuild. On Windows 95 and Windows 98 systems, the mex and mbuild scripts require more than the default amount of environment space. If you get the error, out of environment space, add this line to your config.sys file. shell=c:\command.
Troubleshooting works from the UNIX shell prompt but does not work from the MATLAB prompt, you may have a problem with your .cshrc file. When MATLAB launches a new C shell to perform compilations, it executes the .cshrc script. If this script causes unexpected changes to the PATH, an error may occur. You can test whether this is true by performing a set SHELL=/bin/sh prior to launching MATLAB. If this works correctly, then you should check your .cshrc file for problems setting the PATH.
2 Installation and Configuration 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.
3 Getting Started with MEX-Files A Simple Example - The Sierpinski Gasket Invoking the M-File . . . . . . . . . . . Compiling the M-File into a MEX-File . . . . Invoking the MEX-File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3 3-4 3-5 3-5 Compiler Options and Macros . . . . . . . . . . . . 3-7 Generating Simulink S-Functions . . . . . . . . . . 3-8 Simulink-Specific Options . . . . . . . . . . . . . . . 3-8 Specifying S-Function Characteristics . . . . . . . . . .
3 Getting Started with MEX-Files This chapter gets you started compiling M-files with the MATLAB Compiler. By the end of this chapter, you should know how to: • Compile M-files into MEX-files • Invoke MEX-files • Generate Simulink S-functions This chapter also lists the limitations and restrictions of the MATLAB Compiler.
A Simple Example - The Sierpinski Gasket 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.
3 Getting Started with MEX-Files The curve can be graphed in many ways. Sierpinski's method is: • Start with a triangle and from it remove a triangle that is one-half the height of the original and inverted. This leaves three triangles. • From each of the remaining three triangles, remove a triangle that is one-fourth the height of these new triangles and inverted. This leaves nine triangles. • The process continues and at infinity the surface area becomes zero and the length of the curve is infinite.
A Simple Example - The Sierpinski Gasket Note The timings listed in this book were recorded on a Pentium Pro 200 MHz PC running Microsoft Windows NT. In each case, the code was executed two times and the results of the second execution were captured for this book. All of the timings listed throughout this book are for reference purposes only. They are not absolute; if you execute the same example under the same conditions, your times will probably differ from these values.
3 Getting Started with MEX-Files tic; x = gasket(50000); toc MATLAB runs the MEX-file version (gasket.mex) rather than the M-file version (gasket.m). Given an M-file and a MEX-file with the same root name (gasket) in the same directory, the MEX-file takes precedence. This produces elapsed_time = 5.2880 The MEX-file runs about 33% faster than the M-file version. Note These are optimized times.
Compiler Options and Macros 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 2.1 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.
3 Getting Started with MEX-Files 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 Using Simulink. For more information about Simulink S-functions, see Writing S-Functions.
Generating Simulink S-Functions 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.
3 Getting Started with MEX-Files Data Type The input and output vectors for the Simulink S-function must be double-precision vectors or scalars. You must ensure that the variables you use in the M-code for input and output are also double-precision values. Note Simulink S-functions that are generated via the -S option of the Compiler are not currently compatible with Real-Time Workshop®. They can, however, be used to rapidly prototype code in Simulink.
Converting Script M-Files to Function M-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.
3 Getting Started with MEX-Files in the MATLAB workspace.
4 Stand-Alone Applications Differences Between MEX-Files and Stand-Alone Applications . . . . . . . . . . 4-3 Building Stand-Alone C/C++ Applications . . . . . . . 4-5 Building Stand-Alone Applications on UNIX . . . . . 4-8 Building Stand-Alone Applications on PCs . . . . . . 4-16 Building Shared Libraries . . . . . . . . . . . . . 4-27 Troubleshooting . . . . . . . . . . . . . . . . . . 4-28 Coding with M-Files Only . . . . . . . . . . . . . . 4-31 Alternative Ways of Compiling M-Files . . . . . . . .
4 Stand-Alone Applications This chapter explains how to use the MATLAB Compiler to code and build stand-alone applications. The first part of the chapter concentrates on using the mbuild script to build stand-alone applications and the second part concentrates on the coding of the applications. Stand-alone applications run without the help of the MATLAB interpreter. In fact, stand-alone applications run even if MATLAB is not installed on the system.
Differences Between MEX-Files and 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.
4 Stand-Alone Applications The MATLAB Compiler translates input M-files into C source code suitable for your own stand-alone applications. After compiling this C source code, the resulting object file is linked with the object libraries. For more information about which libraries must be included when you distribute a C application, see “Distributing Stand-Alone UNIX Applications” on page 4-14 or “Distributing Stand-Alone Windows Applications” on page 4-26.
Building Stand-Alone C/C++ 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.
4 Stand-Alone Applications This figure shows the sequence on both platforms. The sections following the flowchart provide more specific details for the individual platforms. Start 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.
Building Stand-Alone C/C++ Applications Getting Started Introducing mbuild The MathWorks utility, mbuild, lets you customize the configuration and build process. The mbuild script provides an easy way for you to specify an options file that lets you: • 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.
4 Stand-Alone Applications 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. This section includes: • Configuring for C or C++ • Preparing to Compile • Verifying mbuild • Verifying the MATLAB Compiler • Distributing Stand-Alone UNIX Applications • About the mbuild Script Configuring for C or C++ The mbuild script deduces the type of files you are compiling by the file extension.
Building Stand-Alone Applications on UNIX Locating Options Files mbuild locates your options file by searching the following: • The current directory • $HOME/.matlab/R12 • /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” in Chapter 2 for information about supported compilers and important limitations.
4 Stand-Alone Applications The setup option creates a user-specific options file for your ANSI C or C++ compiler. Executing mbuild -setup presents a list of options files currently included in the bin subdirectory of MATLAB. mbuild -setup Using the 'mbuild -setup' command selects an options file that is placed in ~/.matlab/R12 and used by default for 'mbuild'. An options file in the current working directory or specified on the command line overrides the default options file in ~/.matlab/R12.
Building Stand-Alone Applications on UNIX Modifying the Options File. Another use of the setup option is if you want to change your options file settings. For example, if you want to make a change to the current linker settings, or you want to disable a particular set of warnings, you should use the setup option.
4 Stand-Alone Applications specified options file for the current execution of mbuild only; it does not reset the default compiler. Verifying mbuild There is C source code for an example ex1.c included in the /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.
Building Stand-Alone Applications on UNIX Note On all UNIX platforms, the Compiler library is shipped as a shared object (.so) file or shared library (.sl). Any Compiler-generated, stand-alone application must be able to locate the C/C++ libraries along the library path environment variable (SHLIB_PATH, LIBPATH, or LD_LIBRARY_PATH) in order to 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.
4 Stand-Alone Applications typically by typing its name at the UNIX prompt. The application should run and display the message Hello, World When you execute the mcc command to link files and libraries, mcc actually calls the mbuild script to perform the functions. Distributing Stand-Alone UNIX Applications To distribute a stand-alone application, you must create a package containing these files: • Your application executable.
Building Stand-Alone Applications on UNIX 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. 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.
4 Stand-Alone Applications 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.
Building Stand-Alone Applications on PCs Note You can override the language choice that is determined from the extension by using the -lang option of mbuild. For more information about this option, as well as all of the other mbuild options, see the mbuild reference page.
4 Stand-Alone Applications This simple method works for the majority of users. Assuming filename.c contains a main function, this example uses your installed C or C++ compiler as your default compiler for creating your stand-alone application. If you are a user who does not need to change compilers, or you do not need to modify your compiler options files, you can skip ahead in this section to “Verifying mbuild” on page 4-22.
Building Stand-Alone Applications on PCs Changing Compilers Changing the Default Compiler. To change your default C or C++ compiler, you select a different options file. You can do this at anytime by using the setup command. This example shows the process of changing your default compiler to the Microsoft Visual C/C++ Version 6.0 compiler. mbuild -setup Please choose your compiler for building stand-alone MATLAB applications.
4 Stand-Alone Applications Linking against the C/C++ Graphics Library Are these correct?([y]/n): y The default options file: "C:\WINNT\Profiles\username\ Application Data\MathWorks\MATLAB\R12\compopts.bat" is being updated... Installing the MATLAB Visual Studio add-in ... Updated ... If the specified compiler cannot be located, you are given the message: The default location for is , but that directory does not exist on this machine.
Building Stand-Alone Applications on PCs option into an integrated development environment (IDE) or makefile that you need to maintain outside of MATLAB. Often, however, it is easier to call mbuild from your makefile. See your system documentation for information on writing makefiles. Note Any changes that you make to the local options file compopts.bat will be overwritten the next time you run mbuild -setup.
4 Stand-Alone Applications 2 In the C options file, within just those copied lines from step 1, replace all occurrences of: - COMPFLAGS with CPPCOMPFLAGS - OPTIMFLAGS with CPPOPTIMFLAGS - DEBUGFLAGS with CPPDEBUGFLAGS - LINKFLAGS with CPPLINKFLAGS. This process modifies your C options file to be a universal C/C++ options file. Temporarily Changing the Compiler.
Building Stand-Alone Applications on PCs stand-alone applications are WIN32 Dynamic Link Libraries. Before running a stand-alone application, you must ensure that the directory containing the DLLs is on your path. The directory must be on your operating system $PATH environment variable. On Windows 95, set the value in your AUTOEXEC.BAT file; on Windows NT, use the Control Panel to set it. Running Your Application You can now run your stand-alone application by launching it from the DOS command line.
4 Stand-Alone Applications 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 mbuild on page 7-25.
Building Stand-Alone Applications on PCs 3 For either mex or stand-alone support, you should also run the following commands at the MATLAB prompt. cd(prefdir); mccsavepath; These commands save your current MATLAB path to a file named mccpath in your user preferences directory. (Type prefdir to see the name of your user preferences directory.) This step is necessary because the MATLAB add-in for Visual Studio runs outside of the MATLAB environment, so it would have no way to determine your MATLAB path.
4 Stand-Alone Applications Distributing Stand-Alone Windows Applications To distribute a stand-alone 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. Note: mbuild does not create a bin directory for every stand-alone application. • Any custom MEX-files your application uses. • All the MATLAB Math run-time libraries.
Building Shared Libraries 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.
4 Stand-Alone Applications Troubleshooting Troubleshooting mbuild This section identifies some of the more common problems that might occur when configuring mbuild to create stand-alone applications. Options File Not Writeable. When you run mbuild -setup, mbuild makes a copy of the appropriate options file and writes some information to it. If the options file is not writeable, you are asked if you want to overwrite the existing options file.
Troubleshooting launches a new C shell to perform compilations, it executes the .cshrc script. If this script causes unexpected changes to the PATH environment variable, an error may occur. You can test this by performing a set SHELL=/bin/sh prior to launching MATLAB. If this works correctly, then you should check your .cshrc file for problems setting the PATH environment variable. Cannot Locate Your Compiler (PC).
4 Stand-Alone Applications Licensing Problem. If you do not have a valid license for the MATLAB Compiler, you will get an error message similar to the following when you try to access the Compiler. Error: Could not check out a Compiler License: No such feature exists. If you have a licensing problem, contact The MathWorks. A list of contacts at The MathWorks is provided at the beginning of this manual. MATLAB Compiler Does Not Generate Application.
Coding with M-Files Only 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 MATLAB’s 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.
4 Stand-Alone Applications The -m option flag causes the MATLAB Compiler to generate C source code suitable for stand-alone applications. For example, the MATLAB Compiler generates C source code files main.c, main_main.c, and mrank.c. main_main.c contains a C function named main; main.c and mrank.c contain a C functions named mlfMain and mlfMrank. (The -c option flag inhibits invocation of mbuild.) To build an executable application, you can use mbuild to compile and link these files.
Coding with M-Files Only main.m mrank.m mcc -W main -t main mbuild does this part. main_main.c mcc -t mrank.m main.c mrank.c 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.
4 Stand-Alone Applications For C++ code, add -L cpp to the previous commands, use a C++ compiler instead of a C compiler, and use the MATLAB C/C++ Math Library. See the MATLAB C++ Math Library User’s Guide for details.
Alternative Ways of Compiling M-Files 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.
4 Stand-Alone Applications To compile and link all four C source code files (main.c, rank.c, mrank.c, and main_main.c) into a stand-alone application, use mcc -m main_main.c main.c rank.c mrank.c The resulting stand-alone application uses your customized version of mlfRank rather than the default version of mlfRank stored in the MATLAB Toolbox Library.
Mixing M-Files and C or C++ 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++.
4 Stand-Alone Applications 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.
Mixing M-Files and C or C++ mrank.m mcc -t -W lib:Pkg -T link:exe mrank mrankp.c mbuild does this part. mrankp.c mrank.c, Pkg.c, Pkg.h 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.
4 Stand-Alone Applications mrankp.c The code in mrankp.c calls mrank and outputs the values that mrank returns. /* * MRANKP.C * "Posix" C main program illustrating the use of the MATLAB Math * Library. * Calls mlfMrank, obtained by using MCC to compile mrank.m. * * $Revision: 1.3 $ * */ #include #include #include "matlab.h" /* Prototype for mlfMrank */ extern mxArray *mlfMrank( mxArray * ); main( int argc, char **argv ) { mxArray *N; /* Matrix containing n.
Mixing M-Files and C or C++ /* 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.
4 Stand-Alone Applications mlfPrintMatrix is one of the many routines in the MATLAB Math Built-In Library, which is part of the MATLAB Math Library product. 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.
Mixing M-Files and C or C++ 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.
4 Stand-Alone Applications You can build this program into a stand-alone application by using the command: mcc -t -W lib:multpkg -T link:exe multarg multargp.c libmmfile.mlib The program first displays the contents of a 3-by-3 matrix a and then displays the contents of scalar b: 6.2832 +34.5575i 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.
Mixing M-Files and C or C++ The mlfMultarg function returns matrices a and b. a has both real and imaginary components; b is a scalar having only a real component.
4 Stand-Alone Applications 4-46
5 Controlling Code Generation Code Generation Overview . . . . . . . . . . . . . 5-3 Compiling Private and Method Functions . . . . . . 5-6 The Generated Header Files . . . . . . . . . . . . . 5-8 Internal Interface Functions . . . . . . . . . . . . 5-11 Supported Executable Types . . . . . . Generating Files . . . . . . . . . . . . . MEX-Files . . . . . . . . . . . . . . . Main Files . . . . . . . . . . . . . . . Simulink S-Functions . . . . . . . . . . . C Libraries . . . . . . . . . . . . . . .
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 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.
5 Controlling Code Generation foo M-File function [a, b] = foo(x, y) if nargout == 0 elseif nargout == 1 a = x; elseif nargout == 2 a = x; b = y; end fun M-File function a = fun(b) a(1) = b(1) .* b(1); a(2) = b(1) + b(2); a(3) = b(2) / 4; sample M-File function y = sample( varargin ) varargin{:} y = 0; Generated Code This chapter investigates the generated header files, interface functions, and wrapper functions for the C MEX, stand-alone C and C++ targets, and C and C++ libraries.
Code Generation Overview This table shows the names of the files generated when you compile a generic M-file (file.m) for the MEX and stand-alone targets. The table also shows the files generated when you compile a set of files (filelist) for the library target. 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.
5 Controlling Code Generation 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.
Compiling Private and Method Functions This table lists the functions you can specify on the command line and their corresponding function and filenames. Function foo C Function C++ Function Filename mlfFoo foo foo.c mlxFoo Nfoo foo.h mlNFoo Vfoo foo.cpp mlfNFoo mlxFoo foo.hpp mlfVFoo @cell/foo mlf_cell_foo _cell_foo _cell_foo.c mlx_cell_foo N_cell_foo _cell_foo.h mlN_cell_foo V_cell_foo _cell_foo.cpp mlfN_cell_foo mlx_cell_foo _cell_foo.
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: 2.
The Generated Header Files 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: 2.
5 Controlling Code Generation 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 mxArray * mprhs[1]; mxArray * mplhs[1]; int i; Input argument processing Call to C implementation function Output argument processing if (nlhs > 1) { mlfError(_mxarray0_); } if (nrhs > 1) { mlfError(_mxarray2_); } for (i = 0; i < 1; ++i) { mplhs[i] = mclGetUninitializedArray(); } for (i = 0; i < 1 && i < nrhs; ++i) { mprhs[i] = prhs[i]; } for (; i < 1; ++i) { mprhs[i] = NULL; } mlfEnterNewContext(0, 1, mprhs[0]); mplhs[0] = Mgasket(nlhs, mprhs[0]); mlfRestorePreviousContex
Internal Interface Functions Input argument processing Call M-function Output argument processing /* * The function "mlfGasket" 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.
5 Controlling Code Generation Input argument processing Call M-function Output argument processing * outputs based on the number of non-NULL inputs it * receives. This function processes any input arguments * and passes them to the implementation version of the * function, appearing above.
Internal Interface Functions * output. The void interface function specifies zero * output arguments to the implementation version of the * function, and in the event that the implementation * version still returns an output (which, in MATLAB, would * be assigned to the "ans" variable), it deallocates the * output. This function processes any input arguments and * passes them to the implementation version of the * function, appearing above.
5 Controlling Code Generation would use the feval interface. The following C++ code is the corresponding feval interface (mlxGasket) from the Sierpinski Gasket example. This function calls the C++ Mgasket function. // // The function "mlxGasket" contains the feval interface // for the "gasket" M-function from file // "\extern\examples\compiler\gasket.m" (lines 1-23). // The feval function calls the implementation version of // gasket through this function.
Internal Interface Functions F Interface Function The Compiler always generates the F interface function, which contains the “normal” C++ interface to the function. This code is the corresponding C++ interface function (gasket) from the Sierpinski Gasket example. This function calls the C++ code. Call M-function Output argument processing // // The function "gasket" contains the normal interface for // the "gasket" M-function from file // "\extern\examples\compiler\gasket.m" (lines 1-23).
5 Controlling Code Generation Input argument processing Call M-function Input argument processing Output argument processing // interface which dynamically calculates the number of // outputs based on the number of non-NULL inputs it // receives. This function processes any input arguments // and passes them to the implementation version of the // function, appearing above.
Internal Interface Functions // // // // // // Input argument processing Call M-function version still returns an output (which, in MATLAB, would be assigned to the "ans" variable), it deallocates the output. This function processes any input arguments and passes them to the implementation version of the function, appearing above.
5 Controlling Code Generation 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.
Supported Executable Types MEX-Files The -W mex -L C options produce the MEX-file wrapper, which includes the mexFunction interface that is standard to all MATLAB plug-ins. For more information about the requirements of the mex interface, see “External Interfaces/API.” In addition to declaring globals and initializing the feval function table, the MEX-file wrapper function includes interface and definition functions for all M-files not included into the set of compiled files.
5 Controlling Code Generation The Compiler processes the string arguments passed to the main() function and sends them into the compiled M-function as strings. For example, consider this M-file, sample.m. function y = sample( varargin ) varargin{:} y = 0; You can compile sample.m into a POSIX main application. If you call sample from MATLAB, you get sample hello world ans = hello ans = world ans = 0 If you compile sample.
Supported Executable Types Simulink S-Functions The -W simulink -L C options produce a Simulink S-function wrapper. Simulink S-function wrappers conform to the Simulink C S-function conventions. The wrappers initialize: • 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.
5 Controlling Code Generation 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.
Supported Executable Types mlib Files Shared libraries, like libraries, let you compile a common set of functions once and then compile other M-functions that depend on them without compiling them again.You accomplish this using mlib files, which are automatically generated when you generate the shared library. Creating an mlib File. When you create a library wrapper file, you also get a .mlib file with the same base name.
5 Controlling Code Generation executable is created, it is linked against the shared library. For example on the PC, the executable timer.exe is created and it is linked against libtimefun.dll. An advantage of using mlib files is that the generated code is smaller because some of the code is now located in the shared library. 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.
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 Note Stand-alone applications require that the MATLAB C/C++ Math Library be purchased for each platform where the Compiler-generated code will be executed. For more information, see the MATLAB C/C++ Math Library documentation.
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 0 1 2 3 4 5 6 7 8 12345678901234567890123456789012345678901234567890123456789012345678901234567890 for (mclForStart( &viter__, mlfScalar(1), mclVa(numPoints, "numPoints"), NULL); mclForNext(&viter__, &i); ) { /* * startPoint = floor((corners(theRand(i),:)+startPoint)/2); */ mlfAssign( &startPoint, mlfFloor( mclMrdivide( mclPlus( mclVe( mlfIndexRef( mclVsv(corners, "corners"), "(?,?)", mlfIndexRef( mclVsv(theRand, "theRand"), "(?)", mclVsv(i, "i")), mlfCreateColonIndex())), mc
Formatting Compiler-Generated Code &corners, mlfDoubleMatrix( 3, 2, _array0_, (double *)NULL)); /* * startPoint = [866 1]; */ mlfAssign( &startPoint, mlfDoubleMatrix( 1, 2, _array1_, (double *)NULL)); /* * theRand = rand(numPoints,1); */ mlfAssign( &theRand, mlfNRand( 1, mclVa(numPoints, "numPoints"), mlfScalar(1), NULL)); /* * theRand = ceil(theRand*3); */ mlfAssign( &theRand, mlfCeil( mclMtimes( mclVv(theRand, "theRand"), mlfScalar(3)))); . . .
5 Controlling Code Generation Default Indentation Not specifying indent formatting options uses the default of four spaces for statements and two spaces for expressions. For example, using mcc -x gasket generates the following code segment.
Formatting Compiler-Generated Code Modified Indentation This example shows the same segment of code using a statement indentation of two and an expression indentation of one. mcc -F statement-indent:2 -F expression-indent:1 -x gasket generates the following code segment.
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 static void Mhello(void) { mxArray * ans = mclGetUninitializedArray(); /* * This is the hello, world function written in M code * $Revision: 1.1 $ * */ mclAssignAns( &ans, mlfNFprintf(0, mlfScalar(1), mxCreateString("Hello, World\\n"), NULL)); mxDestroyArray(ans); } . . .
5 Controlling Code Generation No Annotation To include no source from the initial M-file in the generated output, use mcc -A annotation:none … This code snippet shows the generated code without comments and source code. static void Mhello(void) { mxArray * ans = mclGetUninitializedArray(); mclAssignAns( &ans, mlfNFprintf(0, mlfScalar(1), mxCreateString("Hello, World\\n"), NULL)); mxDestroyArray(ans); } . . .
Including M-File Information in Compiler Output 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. . Line 1 Line 1 Line 5 Line 5 Line 5 Line 5 Line 5 #line 1 "\\extern\\examples\\compiler\\hello.m" static void Mhello(void) { #line 1 "\\extern\\examples\\compiler\\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 File/line # tmmult Inner matrix dimensions must agree. Error in File: "\extern\examples\compiler\tmmult.m", Function: "tmmult", Line: 5. Error in ==> \extern\examples\compiler\tmmult.dll Note When using the -A debugline:on option, the lasterr function returns a string that includes the line number information.
5 Controlling Code Generation Interfacing M-Code to C/C++ Code The MATLAB Compiler 2.1 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 Print Handlers A print handler is a routine that controls how your application displays the output generated by calls to mlf routines. The system provides a default print handler for your application. The default print handler writes output to the standard output stream. If this print handler is suitable for your application, you do not need to write and register another print handler.
Print Handlers The application is built from two files: • mrankwin.c, which contains WinMain, WinPrint (the print handler), and a related function WinFlush • The MATLAB Compiler C translation of mrank.m Both mrankwin.c and mrank.m are located in the /extern/examples/compiler/ directory of your installation. The WinMain routine in mrankwin.c is straightforward: • It registers a print handler.
5 Controlling Code Generation The print handler that you write must: • Take a single argument of type const char * that points to the text to be displayed. • Return void. The print handler routine WinPrint in the example program illustrates one possible approach to writing a print handler for a Windows program. When the example WinMain routine prints the array returned by mlfMrank, mlfPrintMatrix(R); the registered print handler, WinPrint, is called.
Print Handlers • The print handler routine itself that deposits the text passed to it in an output buffer void WinPrint( char *text) { int cnt; /* Allocate a buffer for the output */ if (firsttime) { OutputBuffer = (char *)mxCalloc(1028, 1); upperlim += 1028; firsttime = 0; } /* Make sure there’s enough room in the buffer */ cnt = strlen(text); while (totalcnt + cnt >= upperlim) { char *TmpOut; upperlim += 1028; TmpOut = (char *)mxRealloc(OutputBuffer, upperlim); if (TmpOut != NULL) OutputBuffer = TmpOut;
5 Controlling Code Generation Main Routine Written in M-Code If your main routine is an M-file, you must: • Write a print handler in C. • Register the print handler in your main M-file. Registering the print handler requires several steps, some performed in C and some in M-code. To register a print handler from your main M-file, you call a dummy print handler initialization function written in M-code.
Print Handlers • mrank.m determines the rank of the magic squares from 1 to n. function r = mrank(n) r = zeros(n, 1); for k = 1:n r(k) = rank(magic(k)); end • myph.c contains the print handler and the print handler initialization routine, in that order. In the example, this C file is written by the user. #include "matlab.h" #include “mr_external.
5 Controlling Code Generation Naming the Print Handler Initialization Routine in C. When you write the print handler initialization routine in C, you must follow the naming convention used by the MATLAB C Math Library. This name will appear in a header file that is generated by the MATLAB Compiler when it compiles the stub M-function, initprnt in this example. See the earlier section, “Interfacing M-Code to C/ C++ Code,” for more information.
Print Handlers Initializing the Print Handler in Your Main M-File. Call the dummy print handler initialization routine in the first executable line of your main M-file. For example, in mr.m the call to initprnt immediately follows the function declaration. function mr(m) initprnt; % Call print handler initialization routine m=str2num(m); r=mrank(m) function initprnt %#external Building the Executable You must compile myph.
5 Controlling Code Generation 5-52
6 Optimizing Performance Optimization Bundles . . . . . . . . . . . . . . . . 6-3 Optimizing Arrays . . . . . . . . . . . . . . . . . 6-5 Scalar Arrays . . . . . . . . . . . . . . . . . . . . 6-5 Nonscalar Arrays . . . . . . . . . . . . . . . . . . 6-5 Optimizing Loops . . . . . . . . . . . . . . . . . 6-7 Simple Indexing . . . . . . . . . . . . . . . . . . . 6-7 Loop Simplification . . . . . . . . . . . . . . . . . . 6-7 Optimizing Conditionals . . . . . . . . . . . . . .
6 Optimizing Performance The MATLAB Compiler can perform several different 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. Compiler 2.1 provides a series of optimizations that can help speed up your compiled code. The optimizations improve performance when: • Your code manipulates scalar or nonscalar arrays. • Your code contains simple one- and two-dimensional array indexing.
Optimization Bundles Optimization Bundles All optimizations are controlled separately, and you can enable or disable any of the optimizations. To simplify the process, you can use the provided bundles of Compiler settings that allow you to select the most common optimization options. For more information on bundles, see “-B (Bundle of Compiler Settings)” on page 7-43.
6 Optimizing Performance List All Optimizations To list all available optimizations, use -O list 6-4
Optimizing Arrays Optimizing Arrays Scalar Arrays (fold_scalar_mxarrays) When this optimization is enabled, all constant, scalar-valued array operations are folded at compile time and are stored in a constant pool that is created once at program initialization time. Folding reduces the number of computations that are performed at runtime, thus improving runtime performance.
6 Optimizing Performance 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, _mxarray0_); ...
Optimizing Loops 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.
6 Optimizing Performance Note This optimization causes the variable names in the resulting C program to differ from those in the M-file. Therefore, it is recommended 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 ...
Optimizing Loops ... for (; ; ) { ... if (v_ == e_) { break; } ++v_; } mlfAssign(&i, mlfScalar(v_)); } ...
6 Optimizing Performance Optimizing Conditionals (optimize_conditionals) This optimization reduces the MATLAB conditional operators to scalar C conditional operators when both operands are known to be integer scalars. The Compiler “knows” that nargin, nargout, and for loop control variables (when using the above optimization) are integer scalars. For example, function test(a,b,c,d) if (nargin < 4) d = 0.0; end If you compile this with the -O none option, you get ...
7 Reference Pragmas . %#external %#function %#mex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-4 7-5 7-6 7-7 Functions . mbchar . . . mbcharscalar mbcharvector mbint . . . mbintscalar . mbintvector . mbreal . . . mbrealscalar mbrealvector mbscalar . . mbvector . . reallog . . . realpow . . realsqrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
This chapter provides reference information for the MATLAB Compiler pragmas, functions, and command line tools. Pragmas %#external Call arbitrary C/C++ functions. %#function feval pragma. %#mex Prefer the MEX-file over an existing M-file. Functions 7-2 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.
Command Line Tools mbuild Customize building and linking. mcc Invoke MATLAB Compiler. MATLAB Compiler Options Flags Introduces Compiler options. Macro Options Simplify basic compilation tasks. Code Generation Options Control Compiler output. Optimization Options Improves the performance of the generated C/C++ code. Compiler and Environment Options Control Compiler behavior. mbuild/mex Options Control mbuild and mex.
Pragmas Pragmas Pragmas are compiler-specific commands that provide special information to the Compiler. This section contains the reference pages for the MATLAB Compiler pragmas, %#external, %#function, and %#mex.
%#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.
Functions Functions This section contains the reference pages for the Compiler functions. Many of these functions are included to maintain backward compatibility with previous versions of the Compiler. Note In Compiler 2.1, the functions mbchar, mbcharscalar, mbcharvector, mbint, mbintscalar, mbintvector, mbreal, mbrealscalar, mbrealvector, mbscalar, and mbvector are not used for type imputation, but rather to test if values are a specific data type.
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 runtime, 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 runtime, 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 runtime, 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 runtime, 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 mbint does not consider the value of x an integer because one of the parts (the imaginary) has a fractional component. x = 4 + 7.5i; Example This code in MATLAB causes mbint to generate an error message because n does not hold an integer value. n = 17.4; mbint(n); ??? Error using ==> mbint Argument to mbint must be integer.
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 runtime, 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 runtime, 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 runtime, 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 runtime, 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 runtime, 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 runtime, 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 runtime, 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.
reallog Purpose 7reallog Natural logarithm for nonnegative real inputs. Syntax Y = reallog(X) Description reallog is an elementary function that operates element-wise on matrices. reallog returns the natural logarithm of X. The domain of reallog is the set of all nonnegative real numbers. If X is negative or complex, reallog issues an error message. reallog is similar to the MATLAB log function; however, the domain of log is much broader than the domain of reallog.
realpow Purpose 7realpow Array power function for real-only output. Syntax Z = realpow(X,Y) Description realpow returns X raised to the Y power. realpow operates element-wise on matrices. The range of realpow is the set of all real numbers. In other words, if X raised to the Y power yields a complex answer, then realpow does not return an answer. Instead, realpow signals an error. If X is negative and Y is not an integer, the resulting power is complex and realpow signals an error.
realsqrt Purpose 7realsqrt Square root for nonnegative real inputs. Syntax Y = realsqrt(X) Description realsqrt(X) returns the square root of the elements of X. The domain of realsqrt is the set of all nonnegative real numbers. If X is negative or complex, realsqrt issues an error message. realsqrt is similar to sqrt; however, sqrt’s domain is much broader than realsqrt’s. The domain of sqrt includes all real and all complex numbers.
Command Line Tools Command Line Tools This section contains the reference pages for the Compiler command line tools, namely, mbuild and mcc. This section describes the command line tool options. Appendix A contains a summary of the options in a convenient table form.
mbuild Purpose 7mbuild Compile and link source files that call functions in the MATLAB C/C++ Math Library or MATLAB C/C++ Graphics Library into a stand-alone executable or shared library. Syntax mbuild [option1 ... optionN] sourcefile1 [... sourcefileN] [objectfile1 ... objectfileN] [libraryfile1 ... libraryfileN] [exportfile1 ... exportfileN] Description mbuild is a script that supports various options that allow you to customize the building and linking of your code.
mbuild 7-26 Option Description -f <> Specify location and name of options file to use. Overrides the mbuild default options file search mechanism. -g Create a debuggable executable. If this option is specified, mbuild appends the value of options file variables ending in DEBUGFLAGS with their corresponding base variable. This option also disables the mbuild default behavior of optimizing built object code. -h[elp] Help; prints a description of mbuild and the list of options.
mbuild 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. Print out any commands that mbuild would execute, but do not actually execute any of them.
mbuild Option Description -setup Interactively specify the compiler options file to use as default for future invocations of mbuild by placing it in \Application Data\ MathWorks\MATLAB\R12 (Windows) or $HOME/.matlab/R12 (UNIX). When this option is specified, no other command line input is accepted. 7-28 -U Remove any initial definition of the C preprocessor symbol . (Inverse of the -D option.
mbuild Option Description # 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'. Note Some of these options (-f, -g, and -v) are available on the mcc command line and are passed along to mbuild.
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 mode) or the DOS or UNIX command line (stand-alone mode). [mfile2 ... mfileN] [C/C++file1 ... C/C++fileN] 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. This table shows the relationship between the macro approach to accomplish a standard compilation and the multioption alternative.
mcc Understanding a Macro Option. The -m option tells the Compiler to produce a stand-alone C application. The -m macro is equivalent to the series of options -t -W main -L C -T link:exe -h libmmfile.mlib This table shows the five options that compose the -m macro and the information that they provide to the Compiler. Table 7-2: The -m Macro Option Function -t Translate M code to C/C++ code. -W main Produce a wrapper file suitable for a stand-alone application.
mcc mcc searches for the mccstartup file in these two directories in the order shown above. If it finds an mccstartup file, it reads it and processes the options within the file as if they had appeared on the mcc command line before any actual command line options. Both the mccstartup file and the -B option are processed the same way. Note If you need to change the meaning of a macro to satisfy your individual requirements, you should create or modify your mccstartup file in the preferences directory.
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-1, Macro Options, on page 7-31, 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 would be equivalent to mcc -m -I /home/user/dir1 -I /home/user/dir2 myfile.m The Compiler finds the myfile.m in dir1 and compiles it instead of the one in dir2 because of the behavior of the -I option. If you are concerned that this might be happening, you can specify the -v option and then see which M-file the Compiler parses. The -v option prints the full pathname to the M-file.
mcc MATLAB Compiler Option Flags The MATLAB Compiler option flags perform various functions that affect the generated code and how the Compiler behaves. This table shows the categories of the Compiler options. Table 7-3: 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 For example, to translate an M-file named mymfile.m into C and to create a stand-alone executable that can be run without MATLAB, use mcc -m mymfile The -m option is equivalent to the series of options -W main -L C -t -T link:exe -h libmmfile.mlib -p (Stand-Alone C++). Produce a stand-alone C++ application. It includes helper functions by default (-h), and then generates a stand-alone C++ wrapper (-W main).
mcc The -B sgl option is equivalent to the series of options -m -W mainhg libmwsglm.mlib -B sglcpp (Stand-Alone C++ Graphics Library). Produce a stand-alone C++ application that uses Handle Graphics. The -B sglcpp option is equivalent to the series of options -p -W mainhg libmwsglm.mlib -B pcode (MATLAB P-Code). Produce MATLAB P-code. The -B pcode option is equivalent to the series of options -t -L P Code Generation Options -A (Annotation Control for Output Source).
mcc To control the #line preprocessor directives that are included in the generated C/C++ source, use mcc -A line:setting … The table shows the available #line directive settings. Table 7-5: Line Annotation Options Setting Description on Adds #line preprocessor directives to the generated C/C++ source code to enable source M-file debugging. Note: The page width option is ignored when this is on. off Adds no #line preprocessor directives to the generated C/C++ source code. The default is off.
mcc To include none of your M-code and no #line preprocessor directives, use mcc -A annotation:none -A line:off … To include the standard #line preprocessor directives in your generated C/C++ source code as well as source file and line number information in your run-time error messages, use mcc -A line:on -A debugline:on … -F
mcc -l (Line Numbers) . Generate C/C++ code that prints filename and line numbers on run-time errors. This option flag is useful for debugging, but causes the executable to run slightly slower. This option is equivalent to mcc -A debugline:on … -L (Target Language). Specify the target language of the compilation. Possible values for language are C or Cpp. The default is C. Note that these values are case insensitive. -O
mcc -W (Function Wrapper). Control the generation of function wrappers for a collection of Compiler-generated M-files. You provide a list of functions and the Compiler generates the wrapper functions and any appropriate global variable definitions. This table shows the valid type options. Table 7-9: Function Wrapper Types Description mex Produces a mexFunction() interface. main Produces a POSIX shell main() function. simulink Produces a Simulink C MEX S-function interface.
mcc Compiler and Environment Options -B (Bundle of Compiler Settings). Replace -B on the mcc command line with the contents of the specified file. The file should contain only mcc command line options and corresponding arguments and/or other filenames. The file may contain other -B options.You can place options that you always set in an mccstartup file. For more information, see ““Setting Up Default Options” on page 7-32. -c (C Code Only).
mcc would set up the search path so that directory1 is searched first for M-files, followed by directory2. This option is important for stand-alone compilation where the MATLAB path is not available. -o . Specify the basename of the final executable output (MEX-file or application) of the Compiler. A suitable, possibly platform-dependent, extension is added to the specified basename (e.g., .exe for PC stand-alone applications, .mexsol for Solaris MEX-files). -t (Translate M to C/C++).
mcc The -v option passes the -v option to mex or mbuild and displays information about mex or mbuild. -w (Warning). Display warning messages. This table shows the various ways you can use the -w option. Table 7-11: Warning Option Syntax Description (no -w option) Default; displays only serious warnings. -w list Generates a table that maps to warning message for use with enable, disable, and error. The “Error and Warning Messages” appendix lists the same information.
mcc mbuild/mex Options -f (Specifying Options File). Use the specified options file when calling mex or mbuild. This option allows you to use different compilers for different invocations of the MATLAB Compiler. This option is a direct pass-through to the mex or mbuild script. See “External Interfaces/API” for more information about using this option with the mex script. Note Although this option works as documented, it is suggested that you use mex -setup or mbuild -setup to switch compilers.
mcc Make a C translation and a Simulink S-function for myfun.m (using dynamically sized inputs and outputs). mcc -S myfun Make a C translation and a Simulink S-function for myfun.m (explicitly calling for one input and two outputs). mcc -S -u 1 -y 2 myfun Make a C translation and stand-alone executable for myfun.m. Look for myfun.m in the /files/source directory, and put the resulting C files and executable in the /files/target directory.
mcc Make a C translation and a stand-alone executable from myfun1.m and myfun2.m (by generating each output file with a separate mcc call). mcc mcc mcc mcc mcc mcc mcc -t -t -W -T -T -T -T -L C myfun1 % Yields myfun1.c -L C myfun2 % Yields myfun2.c main -L C myfun1 myfun2 % Yields myfun1_main.c compile:exe myfun1.c % Yields myfun1.o compile:exe myfun2.c % Yields myfun2.o compile:exe myfun1_main.c % Yields myfun1_main.o link:exe myfun1.o myfun2.o myfun1_main.o Note On PCs, filenames ending with .
A MATLAB Compiler Quick Reference Common Uses of the Compiler . . . . . . . . . . . . A-2 mcc . . . . . . . . . . . . . . . . . . . . . . . .
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.
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 Option Description h Compiles helper functions I directory Adds new directory to path l Generates code that reports file and line numbers on run-time errors L language Specifies output target language m Macro to generate a C stand-alone application M string Passes string to mex or Comment/Options Equivalent to: -A debugline:on language = C Cpp Equivalent to: -W main -L C -t -T link:exe -h libmmfile.mlib Use to define compile-time options.
A MATLAB Compiler Quick Reference Option Description Comment/Options T target Specifies output stage target = where bin = u number Specifies number of inputs for Simulink S-function v Verbose; Displays compilation steps w option Displays warning messages codegen compile:bin link:bin mex exe lib option = list level level:string where level = disable enable error No w option displays only serious warnings (default).
mcc Option Description z path Specifies path for library and include files ? Displays help message Comment/Options A-7
A MATLAB Compiler Quick Reference A-8
B Error and Warning Messages Compile-Time Errors . . . . . . . . . . . . . . . . B-3 Warning Messages . . . . . . . . . . . . . . . . . B-12 Run-Time Errors . . . . . . . . . . . . . . . . . .
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.
Compile-Time Errors Compile-Time Errors Error: An error occurred while shelling out to mex/mbuild (error code = errorno). Unable to build executable (specify the -v option for more information). The Compiler reports this error if mbuild or mex generates an error. Error: An error occurred writing to file "filename": reason. The file could not be written. The reason is provided by the operating system. For example, you may not have sufficient disk space available to write the file.
B Error and Warning Messages Error: File: filename Line: # Column: # () indexing must appear last in an index expression. If you use ordinary array indexing () to index into an expression, it must be last in the index expression. For example, you can use X(1).value and X{2}(1), but you cannot use X.value(1) or X(1){2}. Error: File: filename Line: # Column: # A CONTINUE may only be used within a FOR or WHILE loop. Use CONTINUE to pass control to the next iteration of a FOR or WHILE loop.
Compile-Time Errors Error: File: filename Line: # Column: # An array for multiple LHS assignment cannot contain token. If the left-hand side of a statement is a multiple assignment, the vector cannot contain this token. For example, you cannot assign to constants. [p1] = myfunc(a) [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.
B Error and Warning Messages Error: File: filename Line: # Column: # Missing variable or function. An illegal name was used for a variable or function. For example, x _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.
Compile-Time Errors Error: File: filename Line: # Column: # The single colon operator (:) can only be used within an array index expression. You can only use the : operator by itself as an array index. For example, A(:) = 5; is okay, but y = :; is not. Error: File: filename Line: # Column: # The variable variablename was mentioned more than once as an input. The argument list has a repeated variable.
B Error and Warning Messages Error: Improper usage of option -optionname. Type "mcc -?" for usage information. You have incorrectly used a Compiler option. For more information about Compiler options, see the section, “MATLAB Compiler Option Flags,” in Chapter 7 or type mcc -? at the command prompt. Error: "languagename" is not a known language. The dialect option was given a language argument for which there is no support yet. For example, mcc -m -D japanese sample.m mcc -m -D german sample.
Compile-Time Errors Error: The environment variable MATLAB must be set to the MATLAB root directory. On UNIX, the MATLAB and LM_LICENSE_FILE variables must be set. The mcc shell script does this automatically when it is called the first time. Error: The file filename cannot be written. When generating an mlib file, the Compiler cannot write out the mlib file. Error: The license manager failed to initialize (error code is errornumber).
B Error and Warning Messages Error: The -option option cannot be combined with other options. The -V2.0 option must appear separate from other options on the command line. For example, mcc -V2.0 -L Cpp … mcc -V2.0L Cpp … % Correct % Incorrect Error: The -optionname option requires an argument (e.g. "proper_example_usage"). You have incorrectly used a Compiler option.
Compile-Time Errors Error: Unknown typesetting option: optionname. The valid typesetting options available with -F are expression-indent:n, list, page-width, and statement-indent:n. Error: Unknown warning enable/disable string: warningstring. -w enable:, -w disable:, and -w error: require you to use one of the warning string identifiers listed in the “Warning Messages” on page B-12. Error: Unrecognized option: -option. The option is not one of the valid options for this version of the Compiler.
B Error and Warning Messages Warning Messages This section lists the warning messages that the MATLAB Compiler 2.1 can generate. Using the -w option for mcc, you can control which messages are displayed. Each warning message contains a description and the warning message identifier string (in parentheses) that you can enable or disable with the -w option.
Warning Messages Warning: File: filename Line: # Column: # The call to function "functionname" on this line could not be bound to a function that is known at compile time. A run-time error will occur if this code is executed. (no_matching_function) The called function was not found on the search path. Warning: File: filename Line: # Column: # Attempt to clear value when it has not been previously defined. (clear_undefined_value) The variable was cleared with the clear command prior to being defined.
B Error and Warning Messages Warning: File: filename Line: # Column: # The call to function "functionname" on this line passed quantity1 inputs and the function is declared with quantity2. A run-time error will occur if this code is executed. (too_many_inputs) There is an inconsistency between the number of formal and actual inputs to the function.
Warning 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.
B Error and Warning Messages Warning: File: filename Line: # Column: # The second output argument from the "functionname" function is only available in MEX mode. A run-time error will occur if this code is executed in stand-alone mode. (unix_dos_second_argument) The DOS command can be called with two output arguments. That form cannot be compiled in stand-alone mode. This warning occurs if the DOS command was called with two output arguments in a file that is being compiled in stand-alone mode.
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.
B Error and Warning Messages Warning: The name of a shared library should begin with the letters "lib". "libraryname" doesn’t. (missing_lib_sentinel) This warning is generated if the name of the specified library does not begin with the letters “lib”. This warning is specific to UNIX and does not occur on Windows.
Run-Time Errors Run-Time Errors Note The error messages described in this section are generated by the Compiler into the code exactly as they are written, but are not the only source of run-time errors. You also can receive run-time errors can from the C/C++ Math Libraries; these errors are not documented in this book. Math Library errors do not include the source file and line number information.
B Error and Warning Messages Run-time Error: File: filename Line: # Column: # The function "functionname" was called with more than the declared number of outputs (quantity1). There is an inconsistency between the declared number of formal outputs and the actual number of outputs. Run-time Error: File: filename Line: # Column: # The load statement did not specifically list the names of variables to be loaded as constant strings.
Index Symbols #line directives 5-36 bcc53opts.bat 2-17 %#external 7-5 bcc54opts.bat 2-17 %#function 7-6 bcc55opts.bat 2-17 %#mex 7-7 bccopts.bat 2-17 Borland compiler 2-15 environment variable 2-27 bundling compiler options -B option flag 7-43 %#mex pragma 7-7 .cshrc 4-12 .
Index I-2 setting indentation 5-29 setting width 5-29 command duality 5-21 compiled code vs. interpreted code 1-14 compiler C++ requirements 4-7 changing default on PC 4-19 changing default on UNIX 4-9 changing on PC 2-21 choosing on PC 4-17 choosing on UNIX 4-9 selecting on PC 2-20 Compiler 2.1. See MATLAB Compiler. Compiler library on UNIX 4-13 Compiler. See MATLAB Compiler. compiling complete syntactic details 7-30–7-48 embedded M-file 7-35 getting started 3-1–3-6 compopts.
Index file G license.dat 2-7, 2-18 -G option flag 7-46 mccpath 7-33 -g option flag 7-40 mlib 5-23, 5-25 gasket.m 3-3 wrapper 1-7 gcc compiler 2-6 for. See loops.
Index interface function 5-11 interfacing M-code to C/C++ code 5-40 internal error B-2 invoking MEX-files 3-5 M-files 3-4 logarithms 7-21 loops in M-files 3-4 M -M option flag 7-46 L -L option flag 7-41 -l option flag 7-41 lasterr function 5-39 lccopts.bat 2-17 library path 4-13 shared locating on PC 4-22 locating on UNIX 4-12 shared C 1-14 static C++ 1-14 wrapper 5-26 libtbx 1-16 license problem 1-6, 2-18, 2-28, 4-30 license.
Index generating source files 5-20 getting started 3-1 good M-files to compile 1-15 installing on PC 2-14 UNIX 2-5, 2-7 installing on Microsoft Windows 2-18 license 1-5 limitations 1-17 macro 7-31 new features 1-3 options 3-7, 7-36–7-48 options summarized A-4 setting path in stand-alone mode 7-33 Simulink S-function output 7-37 Simulink-specific options 3-8 supported executable types 5-20 syntax 7-30 system requirements Microsoft Windows 2-14 UNIX 2-5 troubleshooting 2-28, 4-29 verbose output 7-44 warning
Index suppressing invocation of 7-43 verifying on Microsoft Windows 2-23 on UNIX 2-11 MEX wrapper 1-7, 5-21 MEX-file bus error 2-26 comparison to stand-alone applications 4-3 compatibility 1-7 computation error 2-26 configuring 2-3 creating on UNIX 2-10 example of creating 3-5 extension Microsoft Windows 2-23 UNIX 2-11 for code hiding 1-14 generating with MATLAB Compiler 2-3 invoking 3-5 overview 1-7 precedence 3-6 problems 2-26–2-27 segmentation error 2-26 timing 3-5 troubleshooting 2-26 MEX-function 7-37
Index measuring performance 3-4 nonscalar arrays 6-5 P -O 6-3 page width setting 5-29 pass through -M option flag 7-46 path setting in stand-alone mode 7-33 pathnames handling full 7-34 PC options file 2-17 running stand-alone application 4-23 supported compilers 2-15 PC compiler limitations 2-15 personal license password 2-18 PLP 2-18 porting code 5-27 POSIX main application 5-21 POSIX main wrapper 5-21 pragma %#external 5-40, 7-5 %#function pragma 7-6 %#mex 7-7 feval 7-6 print ha
Index private function ambiguous names 5-7 compiling 5-6 problem with license 2-18 R rank 4-35 reallog 7-21 real-only functions reallog 7-21 realpow 7-22 realsqrt 7-23 realpow 7-22 realsqrt 7-23 registry 2-27 resolving conflicting options 7-34 run-time errors controlling information 5-38 S -S option flag 3-8, 7-37 sample time 3-9 specifying 3-9 script M-file 1-17, 3-11 converting to function M-files 3-11 setting default options 7-32 S-function 3-8 generating 3-8 passing inputs 3-8 passing outputs 3-8 s
Index stand-alone C++ applications system requirements 4-4 stand-alone Compiler setting path 7-33 stand-alone graphics applications generating C applications 7-37 generating C++ applications 7-38 startup script 4-12 static library 1-14 supported executables 5-20 system requirements Microsoft Windows 2-14 UNIX 2-5 supported compilers 2-6 system requirements 2-5 UNIX compiler limitations 2-6 unsupported functions in stand-alone mode 1-18 upgrading 1-16 from Compiler 1.0/1.1 1-16 from Compiler 1.
Index wrapper file 1-7 MEX 1-7 target types 1-13 wrapper function 5-20 X -x option flag 7-37 Y -Y option flag 7-45 -y option flag 3-9, 7-42 Z -z option flag 7-46 I-10