Home

MATLAB APPLICATION DEPLOYMENT - WEB EXAMPLE GUIDE User`s guide

image

Contents

1. Does the MATLAB command mcc x invhilb m generate invhilb mex See Compiler Troubleshooting Figure 2 1 MATLAB Compiler Installation Sequence for Creating MEX Files 2 installation and Configuration UNIX Workstation This section examines the system requirements installation procedures and configuration procedures for the MATLAB Compiler on UNIX systems System Requirements You cannot install the MATLAB Compiler unless MATLAB 6 5 Release 13 is already installed on the system The MATLAB Compiler imposes no operating system or memory requirements beyond those that are necessary to run MATLAB The MATLAB Compiler consumes a small amount of disk space Table 2 1 Requirements for Creating UNIX Applications shows the requirements for creating UNIX applications with the MATLAB Compiler Table 2 1 Requirements for Creating UNIX Applications To create You need MEX files ANSI C compiler MATLAB Compiler Stand alone C applications ANSI C compiler MATLAB Compiler Stand alone C applications C compiler MATLAB Compiler Note Although the MATLAB Compiler supports the creation of stand alone C applications it does not support the creation of C MEX files 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
2. leere 7 4 vi Contents MATLAB Compiler Quick Reference A B Compile Time Errors 0 0 00 cece eens B 2 Warning Messages esses B 11 Run Time Errors esee eee B 18 vii vili Contents Preface This chapter provides information about this documentation set The sections are as follows Related Products p x MathWorks products related to the Compiler Using this Guide p xi An overview of this book Typographical Conventions p xii Typographical conventions used in this book Preface Related Products The MATLAB Compiler automatically converts MATLAB M files to C and C code The MATLAB Compiler includes the MATLAB C C Math and Graphics Libraries which let you automatically convert your MATLAB applications to C and C code for stand alone applications The MathWorks provides several products that are especially relevant to the MATLAB Compiler For more information about any of these products see either The online documentation for that product The products section of the MathWorks Web site www mathworks com Product Description MATLAB COM Builder MATLAB Excel Builder MATLAB Runtime Server MATLAB Web Server Creating COM components from MATLAB M files Creating MATLAB based add ins for Excel Deploy run time versions of MATLAB applications Use MATLAB with HTML Web applications Using this Gui
3. 0 0 eee 1 4 MATLAB Compiler 8 0 0 0 0 ccc eee eens 1 4 MATLAB Compiler 2 8 2 0 0 0 0 ccc ens 1 4 MATLAB Compiler 2 1 0 0 0 c eee eee 1 5 Compiler Licensing Changes 0 0c eee eee eee 1 7 Uses of the Compiler 0 0 0 ccc ees 1 9 Creating MEX Files 0 0 0 0 000s 1 9 Creating Stand Alone Applications 005 1 11 The MATLAB Compiler Family 1 14 Why Compile M Files ull sslseeesss 1 16 Stand Alone Applications and Libraries 1 16 Excel Plug Ins 0 0 0 0 cee e 1 16 Contents COM Components lessen 1 16 Hiding Proprietary Algorithms 00 000 ee 1 16 Upgrading from Previous Versions of the Compiler 1 17 Upgrading from MATLAB Compiler 2 0 2 1 2 2 2 8 1 17 Upgrading from MATLAB Compiler 1 0 1 1 1 17 Limitations and Restrictions 0000 1 18 MATLAB Code ovs reies E n gel hil oe es rere DE Vie 1 18 Stand Alone Applications 0 0 0 cece eee eee 1 19 Fixing Callback Problems Missing Functions 1 20 Installation and Configuration 2 System Configuration for MEX Files 2 2 UNIX Workstation 0 0 0 0 0 0 0 cc e 2 4 System Requirements 0 0 00 cece eee ee ences 2 4 Installation 15 Y ee epe REESE REF 2 6 mex VerificatloRm sve ues uie boas eee Pe is 2 7 MATLAB
4. This chapter describes the system requirements for the MATLAB Compiler and installation and configuration information It includes information for both MATLAB Compiler platforms UNIX and Microsoft Windows When you install your ANSI C or C compiler you may be required to provide specific configuration details regarding your system This chapter contains information for each platform that can help you during this phase of the installation process The sections Things to Be Aware of provide this information for each platform System Configuration for MEX Files Steps to create MEX files p 2 2 UNIX Workstation p 2 4 Configuration on UNIX systems Microsoft Windows on PCs p 2 13 Configuration on PCs Troubleshooting p 2 25 Dealing with installation and configuration problems 2 installation and Configuration System Configuration for MEX Files This section outlines the steps necessary to configure your system to create MEX files The sequence of steps to install and configure the MATLAB Compiler so that it can generate MEX files is 1 Install the MATLAB Compiler 2 Install an ANSI C or C compiler if you don t already have one installed Note If you encounter problems relating to the installation or use of your ANSI C or C compiler consult the documentation or customer support organization of your C or C compiler vendor 3 Verify that mex can generate MEX files 4 Verify that the MATLA
5. 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 e Stand alone C or C applications run independently of MATLAB MEX Files It is now possible to call MEX files from Compiler generated stand alone applications The Compiler will compile MEX files whenever they are specified on the command line or are located using the h option to find helper functions The MEX files will then be loaded and called by the stand alone code If an M file and a MEX file appear in the same directory and the M file contains at least one function the Compiler will compile the M file instead of the MEX file If the MEX file is desired instead you must use the mex pragma For more information on this pragma see the mex reference page Note The Compiler generated code cannot invoke Compiler generated MEX files Specify the M file s source instead and the Compiler will compile those into the stand alone application Stand Alone C Applications To build stand alone C applications as described in this chapter MATLAB the MATLAB Compiler a C compiler and the MATLAB C C Math Library must be installed on your system The source code for a stand alone C application consists either entirely of M files or some combination
6. Watcom C C versions 10 6 and 11 0 Borland C versions 5 3 5 4 5 5 5 6 and free 5 5 You may see references to these compilers as Borland C Builder versions 3 0 4 0 5 0 and 6 0 For more information on the free Borland compiler and its associated command line tools see http community borland com Microsoft Visual C C MSVO versions 5 0 6 0 and 7 0 Note For a list of all the compilers supported by MATLAB see the MathWorks Technical Support Department s Technical Notes at http www mathworks com support tech notes 1600 1601 shtml Applications generated by the MATLAB Compiler are 32 bit applications and only run on any MATLAB supported Microsoft Windows systems For a complete list of supported Windows platforms see http www mathworks com products system shtml Windows Microsoft Windows on PCs Known Compiler Limitations There are several known restrictions regarding the use of supported compilers Some compilers e g Watcom do not handle denormalized floating point values correctly Denormalized floating point numbers are numbers that are greater than 0 and less than the value of DBL MIN in your compiler s float h file The MATLAB Compiler sometimes will generate goto statements for complicated if conditions 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 catc
7. array indexing This optimization improves the performance of simple one and two dimensional array index expressions Without this optimization all array indexing uses the fully general array indexing function which is not optimized for one and two dimensional indexing With this optimization enabled indexing uses faster routines that are optimized for simple indexing For example function y test x 1i1 12 y x il i2 If you compile this with the 0 none option you get mlfAssign amp y mlfIndexRef mclVa x x 2 molVa ii it mclVa i2 i2 Compiling with 0 none O array indexing on gives mlfAssign amp y mclArrayRef2 mclVa x x mclVa i l i1 mclVa i2 i2 The mclArrayRef2 function is optimized for two dimensional indexing mclArrayRef1 is used for one dimensional indexing Loop Simplification optimize integer for loops This optimization detects when a loop starts and increments with integers It replaces the loop with a much simpler loop that uses C integer variables instead of array valued variables The performance improvements with this optimization can be dramatic Optimizing Loops Note This optimization causes the variable names in the resulting C program to differ from those in the M file Therefore we recommend that you do not use this option when debugging For example function test x for i 1 length x 1 x i x i x i 1 end If you compil
8. Add pathname to the list of directories to search for include files Inline matrix accessor functions mx The generated executable may not be compatible with future versions of the MATLAB C C Math Library or MATLAB C C Graphics Library UNIX Link with object library lib name UNIX Add lt directory gt to the list of directories containing object library routines 7 21 mbuild Table 7 1 mbuild Options Continued Option Description lang lt language gt outdir lt dirname gt output lt resultname gt Specify compiler language lt language gt can be c or cpp By default mouild 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 No execute mode Print out any commands that mbuild would execute but do not actually execute any of them Do not link against the MATLAB C C Graphics Library Handle Graphics Optimize the object code by including the optimization flags listed in the options file If this option is specified mbuild appends the value of options file variables ending in OPTIMFLAGS with their corresponding base variable Note that optimizations are enabled by default are disabled by the g option but are reenabled by 0 Place any generated object resource or ex
9. n 4 2 mbintscalar n Error using mbint Argument to mbint must be integer mbint mbscalar mcc 7 13 mbintvector Purpose Syntax Description Example See Also Assert variable is integer vector mbintvector n The statement mbintvector x causes the MATLAB Compiler to impute that x is an integer vector At run time if nbintvector determines that x holds a value other than an integer vector mbintvector issues an error message and halts execution of the MEX file mbintvector tells the MATLAB interpreter to check whether x holds an integer vector value If x does not mbintvector issues an error message and halts execution of the M file The MATLAB interpreter does not use mbintvector to impute x Note that mbintvector only tests x at the point in an M file or MEX file where an mbintvector call appears In other words an mbintvector call tests the value of x only once If x becomes a two dimensional matrix after the mbintvector test mbintvector cannot issue an error message mbintvector defines an integer vector as any value that meets the criteria of both mbint and mbvector Note that mbintvector considers integer scalars to be integer vectors as well This code in MATLAB causes mbintvector to generate an error message because although all the values of n are integers n is a matrix rather than a vector n magic 2 n 1 3 4 2 mbintvector n Error using mbvector Argument
10. Does the command mbuild exi c generate proper application See Troubleshooting Yes mbuild Test your MATLAB Compiler configuration Does the command mcc m hello generate the hello application See Troubleshooting Compiler Figure 4 1 Sequence for Creating Stand Alone C C Applications Packaging Stand Alone Applications To distribute a stand alone application you must include the application s executable as well as the shared libraries with which the application was linked The necessary shared libraries vary by platform The individual UNIX and Windows sections that follow provide more information about packaging applications 4 5 4 Stand Alone Applications 4 6 Getting Started Introducing mbuild The MathWorks utility mouild lets you customize the configuration and build process The mbuild script provides an easy way for you to specify an options file that lets you Set your compiler and linker settings Change compilers or compiler settings Switch between C and C development Build your application The MATLAB Compiler mcc automatically invokes mbuild under certain conditions In particular mcc mormcc p invokes mbuild to perform compilation and linking See the mcc reference page for complete details on which Compiler options you should use in order to use the mbuild script If you do not want mcc to invoke mbuild autom
11. in callback strings The Compiler processes any function listed in a function pragma For example the call to the change_colormap function in the sample application my_test illustrates this problem To make sure the Compiler processes the change_colormap M file list the function name in the function pragma function my_test Graphics library callback test application s function change colormap peaks p btn uicontrol gcf style pushbutton Position 10 10 133 25 String Make Black amp White CallBack change colormap Note Instead of using the s function pragma you can specify the name of the missing M file on the Compiler command line Finding Missing Functions in an M File To find functions in your application that may need to be listed in a function pragma search your M file source code for text strings specified as callback strings or as arguments to the feval fminbnd fminsearch funm and fzero functions or any ODE solvers To find text strings used as callback strings search for the characters Callback or fen in your M file This will find all the Callback properties defined by Handle Graphics objects such as uicontrol and uimenu In addition this will find the properties of figures and axes that end in Fcn such as CloseRequestFcn that also support callbacks 1 21 Introducing the MATLAB Compiler 1 22 Installation and Configuration
12. mwArray UNDEFINED L _ Call M Function a Mfoo amp b nargout x y ff esse eee SES Input Argument Processing if b NULL b b_ If ears tee Ss ced Output Argument Processing return a 5 19 5 Controlling Code Generation 5 20 VF Interface Function The Compiler produces this interface function only when the M function uses the variable nargout and has at least one output The void interface function specifies zero output arguments to the implementation version of the function and in the event that the implementation version still returns an output which in MATLAB would be assigned to the ans variable it deallocates the output This is the corresponding VF interface function VFoo for the foo m example described earlier in this chapter This function calls the Mfoo function appearing in foo cpp LI LI LI LI LI The function Vfoo contains the void interface for the foo M function from file lt matlab gt extern examples compiler foo m lines 1 8 The void interface is only produced if the M function uses the special variable nargout and has at least one output The void interface function specifies zero output arguments to the implementation version of the function and in the event that the implementation version still returns an output which in MATLAB would be assigned
13. Formatting Compiler Generated Code 5 35 Listing All Formatting Options 0000000 5 35 Setting Page Width aoua ran oaee Ko aaa a 5 35 Setting Indentation Spacing 0 0 cece eee 5 37 Including M File Information in Compiler Output 5 40 Controlling Comments in Output Code 5 40 Controlling line Directives in Output Code 5 42 Controlling Information in Run Time Errors 5 44 Interfacing M Code to C C Code 5 46 Example 54 Ring reete RR e RE UR EIE 5 46 Using Pragmas 5l 2lxewpRReID UG ete oe YU E ENOU EM 5 48 6 Optimization Bundles lssele een 6 2 Optimizing Arrays eot sae RED s 6 4 Scalar Arrays 3s eee x Se RIS RI RUN EI esee 6 4 Nonscalar Arrays 2 ea pn RU ape NERA MUNERE UA 6 4 Scal rs zm li ges inei LEE 6 5 Optimizing Loops sseeee eee 6 6 Simple Indexing cer dbs Leere eee aea 6 6 Loop Simplification 2 0 0 0 0 eens 6 6 Optimizing Conditionals 0 0 0 0 eee 6 9 Optimizing MATLAB Arrays sees 6 10 Scalats ele ene IN P ER ce ips as 6 10 Scalar Doubles y eere prne eet ae ET Eae EEEO OEE TA 6 10 Reference Functions By Category sels 7 2 Pragmas Joni 2a duae eu V RR n d a bte 7 2 Compiler Functions llle 7 2 Command Line Tools 0 0 7 2 Functions By Name
14. click on the MATLAB Access option log in to the Access home page and follow the instructions Via e mail at service mathworks com UNIX Workstation ANSI C or C Compiler To install your ANSI C or C compiler follow the vendor s instructions that accompany your C or C compiler Be sure to test the C or C compiler to make sure it is installed and configured properly Typically the compiler vendor provides some test procedures The following section Things to Be Aware of contains several UNIX specific details regarding the installation and configuration of your ANSI C or C compiler Note On some UNIX platforms a C or C compiler may already be installed Check with your system administrator for more information Things to Be Aware of This table provides information regarding the installation and configuration of a C or C compiler on your system Description Comment Determine which C or C compiler See your system administrator is installed on your system Determine the path to your C or See your system administrator C compiler mex Verification Choosing a Compiler Using the System Compiler Ifthe MATLAB Compiler and your supported C or C compiler are installed on your system you are ready to create C MEX files To create a MEX file you can simply enter mex filename c This simple method of creating MEX files works for the majority of users It uses the system s compiler
15. folding 6 4 script M file 1 18 3 10 converting to function M files 3 10 setting default options 7 27 S function 3 7 generating 3 7 passing inputs 3 7 passing outputs 3 7 shared library 1 16 4 30 distributing with stand alone application 4 5 header file 5 24 locating on PC 4 22 locating on UNIX 4 11 UNIX 4 11 wrapper 5 24 SHLIB PATH run time libraries 4 28 Sierpinski Gasket 5 2 Simulink compatible code 3 7 S function 3 7 u option flag 7 39 wrapper 5 24 y option flag 7 41 Simulink S function output 7 33 restrictions on 3 9 specifying option file f option flag 7 47 specifying output directory d option flag 7 43 specifying output file o option flag 7 44 specifying output stage T option flag 7 44 speculate optimization 6 10 stand alone applications 4 1 distributing on PC 4 27 distributing on UNIX 4 13 distributing on Windows 4 26 generating C applications 7 32 generating C applications 7 32 helper functions 4 41 overview 4 4 C 1 11 C 1 11 process comparison to MEX files 4 2 restrictions on 1 19 restrictions on Compiler 2 3 1 19 UNIX 4 7 writing your own function 4 40 stand alone C applications system requirements 4 2 stand alone C applications system requirements 4 3 stand alone Compiler setting path 7 28 stand alone graphics applications generating C applications 7 35 generating C applications 7 35 startup script 4 11 static library 1 16 supported executables 5 21 system
16. pre allocate the matrix for i 1 100 y i collect_one end function y collect_one external persistent t if isempty t t 0 end t t 0 05 end y sin t When this file is compiled the Compiler creates the additional header file collect_external h which contains the interface between the Compiler generated code and your code In this example it would contain extern mxArray Mcollect collect one int nargout 5 47 5 Controlling Code Generation 5 48 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 Zinclude collect external h include lt math h gt extern double measure_from_device void mxArray Mcollect_collect_one int nargout i return mlfScalar measure from device double measure_from_device void static double t 0 0 t t 0 05 return sin t In general the Compiler will use the same interface for this function as it would generate To generate the C code and header file use mcc mc collect m By examining the Compiler generated C code you should easily be able to determine how to implement this interface To compile collect mtoa MEX file use mcc x collect m measure c Using Pragmas Using feval In stand alone C and C modes the pragma function function name list informs t
17. 2 If you were to connect the referencing S Function block to signals that do not correspond to the correct number of inputs or outputs Simulink will generate an error when the simulation starts Note The MATLAB Compiler S option does not support the passing of parameters which is normally available with Simulink S functions Specifying S Function Characteristics Sample Time Similar to the MATLAB Fen block the automatically generated S function has an inherited sample time Generating Simulink S Functions Data Type The input and output vectors for the Simulink S function must be double precision vectors or scalars You must ensure that the variables you use in the M code for input and output are also double precision values Note Simulink S functions that are generated via the S option of the Compiler are not currently compatible with Real Time Workshop They can however be used to rapidly prototype code in Simulink 3 Working with MEX Files Converting Script M Files to Function M Files MATLAB provides two ways to package sequences of MATLAB commands Function M files Script M files These two categories of M files differ in two important respects You can pass arguments to function M files but not to script M files Variables used inside function M files are local to that function you cannot access these variables from the MATLAB interpreter s workspace unless they are passed back by t
18. 4 6 Building Stand Alone Applications on UNIX 4 7 Configuring for C or C 2 0 0 0 cece eens 4 7 Preparing to Compile 0 ccc eee ee 4 8 Verifying mbuild 2 1 0 0 ccc eee nes 4 11 Verifying the MATLAB Compiler 0000000 4 12 About the mbuild Script 0 0 0 ccc ccs 4 13 Packaging UNIX Applications 0 0200 e eae 4 13 iii iv Contents Building Stand Alone Applications on PCs 4 15 Configuring for C or C 2 0 0 0 ccc cee eee 4 15 Preparing to Compile 0 e eee eens 4 16 Verifying mbuild esee yy eed ak peru e ae Rees 4 22 Verifying the MATLAB Compiler 000 4 23 About the mbuild Script 0 0 0 cece nes 4 23 Using an Integrated Development Environment 4 23 Packaging Windows Applications for Distribution 4 26 Distributing Stand Alone Applications 4 27 Packaging the MATLAB Run Time Libraries 4 27 Installing Your Application 0 000 4 27 Problem Starting Stand Alone Application 4 28 Building Shared Libraries lusluss 4 30 Building COM Objects 0 0 0 0 cece ene ene 4 31 Building Excel Plug Ins 000000000 4 32 Troubleshooting eee eee 4 33 Troubleshooting mbuild 0 0 cece eee ees 4 33 Troubleshooting the Compiler 0 000 e eee 4 35 Co
19. 6 2 0 list 6 3 0 none 6 2 optimization bundles 6 2 scalar arrays 6 4 scalar doubles 6 10 scalars 6 5 6 10 simple indexing 6 6 when not to optimize 6 1 options 3 6 Compiler 2 3 A 4 macro 3 6 resolving conflicting 7 29 setting default 7 27 I 7 Index options file combining customized on PC 4 21 locating 2 16 locating on PC 4 16 locating on UNIX 4 8 making changes persist on PC 4 20 UNIX 4 10 modifying on PC 2 21 4 19 UNIX 4 10 PC 2 16 purpose 4 6 temporarily changing on PC 4 21 UNIX 4 10 UNIX 2 6 out of environment space on Windows 2 25 outputs dynamically sized 3 7 setting number 3 8 P p option flag 7 32 page width setting 5 35 pass through M option flag 7 47 PATH run time libraries 4 28 path setting in stand alone mode 7 28 pathnames handling full 7 29 PC options file 2 16 running stand alone application 4 22 supported compilers 2 14 PC compiler limitations 2 15 percolate simple types optimization 6 10 personal license password 2 17 PLP 2 17 porting code 5 34 POSIX main application 5 22 POSIX main wrapper 5 22 pragma S external 5 46 7 5 function 7 6 mex 7 7 feval 7 6 private function ambiguous names 5 6 compiling 5 5 problem with license 2 17 R rank 4 40 registry 2 26 resolving conflicting options 7 29 resource compiler 4 31 4 32 run time errors controlling information 5 44 S S option flag 3 7 7 33 sample time 3 8 specifying 3 8 Index scalar arrays
20. A MEX o S z LIB O 5 E Simulink o COM 5 5 User C C Code C C Compiler Ye aera one Target Types 2 Stand Alone MATLAB Library Simulink COM C C Program C MEX File C MEX File Library Figure 1 3 MATLAB Compiler Uses The MATLAB Compiler Family Table 1 1 Compiler Wrappers and Targets The Compiler takes your M file s and can generate C or C code It can also generate a wrapper file depending on your specified target This table shows the wrapper files the Compiler can generate their associated targets and the corresponding W option wrapper Wrapper Target W Setting File Main Stand alone W main C or C program MEX MATLAB C W mex MEX file Library C shared W lib libname library or C static library Simulink Simulink C W simulink S function MEX file COM COM object W com lt componentname gt lt classname gt lt major gt lt minor gt W comhg lt componentname gt lt classname gt lt major gt lt minor gt Excel Excel W excel lt componentname gt lt classname gt lt major gt lt minor gt Plug in W excelhg lt componentname gt lt classname gt lt major gt lt minor gt Each numbered node in Figure 1 3 MATLAB Compiler Uses indicates a combination of C C code and a wrapper that generates a specific target type The file s formed by combining the C C code denoted by User C C Code
21. About the mbuild Script The mbuild script supports various options that allow you to customize the building and linking of your code Many users do not need to know any additional details of the mbuild script they use it in its simplest form For complete information about the mbuild script and its options see the mbuild reference page Packaging UNIX Applications To distribute a stand alone UNIX application you must create a package containing these files Your application executable The contents if any of a directory named bin created by mbuildin 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 run time libraries For specific information about packaging these files see Distributing Stand Alone Applications on page 4 27 Distribution Caveats Locating Shared Libraries Remember to locate the shared libraries along the LD_LIBRARY_PATH SHLIB_PATH on HP environment variable so that they can be found and loaded Graphics Support on IBM_RS There is no support for the MATLAB C C Graphics Library on the IBM_RS platform C and Fortran Support on Digital UNIX MATLAB users require access to both the C and Fortran run time shared libraries These are usually provided as part of the operating system installation For Digital UNIX however the C shared libraries are
22. All scalars are also vectors though most vectors are not scalars Example This code in MATLAB causes mbvector to generate an error message because the dimensions of n are 2 by 2 n n magic 2 1 3 4 2 mbvector n Error using gt mbvector Argument to mbvector must be a vector See Also mbint mbintscalar mbintvector mbreal mbrealscalar mbscalar mbrealvector mcc 7 19 mbuild Purpose Syntax Description 7 20 Compile and link source files that call functions in the MATLAB C C Math Library or MATLAB C C Graphics Library into a stand alone executable or shared library mbuild option1 optionN sourcefilei sourcefileN objectfile1 objectfileN libraryfilei libraryfileN exportfile1 exportfileN Note Supported types of source files are c cpp idl rc To specify IDL source files to be compiled with the MIDL Compiler add filename idl to the mbuild command line to specify a DEF file add lt filename gt def to the command line to specify an RC file add lt filename gt rc to the command line Source files that are not one of the supported types are passed to the linker mbuild is a script that supports various options that allow you to customize the building and linking of your code Table 7 1 mbuild Options lists the mbuild options If no platform is listed the option is available on both UNIX and Microsoft Windows Table 7 1 mbuild Options Opt
23. Alone Applications 4 46 Print the results mlfPrintMatrix R Free the matrices allocated during this computation mxDestroyArray N mxDestroyArray R PkgTerminate Terminate the library of M functions An Explanation of mrankp c The heart of mrankp c is a call to the mlfMrank function Most of what comes before this call is code that creates an input argument to mlfMrank Most of what comes after this call is code that displays the vector that mlfMrank returns First the code must call the Compiler generated library initialization function PkgInitialize Initialize the library of M Functions To understand how to call mlfMrank examine its C function header which is mxArray mlfMrank mxArray n rhs According to the function header mlfMrank expects one input parameter and returns one value All input and output parameters are pointers to the mxArray data type See External Interfaces API in the MATLAB online documentation for details on the mxArray data type To create and manipulate mxArray variables in your C code you can call the mx routines described in the External Interfaces API or any routine in the MATLAB C C Math Library For example to create a 1 by 1 mxArray variable named N with real data mrankp calls mlfScalar N mlfScalar n mrankp can now call mlfMrank passing the initialized N as the sole input argument R mlfMrank N mlfMrank re
24. C Version 10 6 Watcom C C Version 11 0 watcopts bat supported for mex only not for mbuild watiicopts bat supported for mex only not for mbuild Borland C Builder 3 bcc53opts bat Borland C Builder 4 bcc54opts bat Borland C Builder 5 bcc55opts bat Borland C Builder 6 bccb56opts bat Locating Options Files To locate your options file the mex script searches the following The current directory The user profile directory see the following section The User Profile Directory Under Windows for more information about this directory mex uses the first occurrence of the options file it finds If no options file is found mex searches your machine for a supported C compiler and uses the factory default options file for that compiler If multiple compilers are found you are prompted to select one The User Profile Directory Under Windows The Windows user profile directory is a directory that contains user specific information such as desktop appearance recently used files and Start menu items The mex and mbuild utilities store their respective options files mexopts bat and compopts bat which are Microsoft Windows on PCs created during the setup process in a subdirectory of your user profile directory named Application Data MathWorks MATLAB R13 Under Windows with user profiles enabled your user profile directory is windir Profiles username Under Windows with user profiles disabled your
25. C C Math Libraries run the following command at the MATLAB command prompt mbuild setup Follow the menus and choose either Microsoft Visual C C 5 0 or 6 0 This configures mbuild to use the selected Microsoft compiler and also installs the necessary add in files into your Microsoft Visual C C directories It is not a problem if these overlap with the files installed by the mex setup command 3 For either mex or stand alone support you should also run the following 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 Building Stand Alone Applications on PCs your MATLAB path If you add directories to your MATLAB path and want them to be visible to the MATLAB add in rerun the cd and mccsavepath commands shown in this step and replace prefdir with the desired pathname 4 To configure the MATLAB add in for Visual Studio to work with Microsoft Visual C C a Select Tools gt Customize from the MSVC menu b Click on the Add ins and Macro Files tab c Select MATLAB for Visual Studio on the Add ins and Macro Files list and click Close The floating MATLAB add in for Visual Studio toolbar appears Select
26. For more information on the files that the Compiler generates see Chapter 5 Controlling Code Generation Invoking the MEX File Invoke the MEX file version of gasket from the MATLAB interpreter the same way you invoke the M file version X gasket 50000 MATLAB runs the MEX file version gasket mex which is gasket d11 on the PO rather than the M file version gasket m Given an M file and a MEX file with the same root name gasket in the same directory the MEX file takes precedence Note To verify that the MEX file version ran use the which command which gasket D work gasket d1l To display the Sierpinski Gasket use imagesc x colormap 1 1 1 0 O 0 axis equal tight A Simple Example The Sierpinski Gasket Figure 3 1 The Sierpinski Gasket for 50 000 Points shows the results e ENERO Figure 3 1 The Sierpinski Gasket for 50 000 Points 3 5 3 Working with MEX Files Compiler Options and Macros The MATLAB Compiler uses a family of options also called option flags to control the functionality of the Compiler The mcc reference page includes a complete description of the Compiler options Throughout this book you will see how these options are used with the Compiler to perform various tasks One particular set of Compiler options macros are particularly useful for performing straightforward compilations Macro options provide a simplified approach to compilation Instead of
27. For more information about this optimization see Chapter 6 Optimizing Performance The MATLAB Compiler allows you to create COM components from MATLAB M files Note To create COM components with the MATLAB Compiler you must have the MATLAB COM Builder product installed on your system MATLAB Compiler 2 3 MATLAB Compiler 2 3 allows you to create Microsoft Excel components from MATLAB M files This Windows only feature translates a collection of M files into a single Microsoft Excel add in Both C and C code generation are supported To support the creation of these components the following Compiler options have been added or enhanced The bundle option B has been enhanced so that you can include replacement parameters for Compiler options that accept names and version numbers and they will be expanded properly New Features e The new option b causes the Compiler to generate a Visual Basic bas file that contains the Microsoft Excel Formula Function interface to a Compiler generated COM object The new option i causes the Compiler to include only the M files that are specified on the command line as exported interfaces Note To create Microsoft Excel components with the MATLAB Compiler you must have the MATLAB Excel Builder product installed on your system MATLAB Compiler 2 1 MATLAB Compiler 2 1 supports much of the functionality of MATLAB 6 The new features of the Compiler are Opt
28. Non ANSI C Compiler on UNIX A common configuration problem in creating C MEX files on UNIX involves using a non ANSI C compiler You must use an ANSI C compiler DLLs Not on Path on Windows MATLAB will fail to load MEX files if it cannot find all DLLs referenced by the MEX file the DLLs must be on the DOS path or in the same directory as the MEX file This is also true for third party DLLs Segmentation Violation or Bus Error If your MEX file causes a segmentation violation or bus error there is most likely a problem with the MATLAB Compiler Contact Technical Support at The MathWorks at support mathworks com Generates Wrong Answers If your program generates the wrong answer s there are several possible causes There could be an error in the computational logic or there may be a defect in the MATLAB Compiler Run your original M file with a set of sample data and record the results Then run the associated MEX file with the sample data and compare the results with those from the original M file Ifthe results are the same there may be a logic problem in your original M file If the results differ there may be a defect in the MATLAB Compiler In this case send the pertinent information via e mail to support mathworks com 2 25 2 installation and Configuration 2 26 mex Works from Shell But Not from MATLAB UNIX If the command mex x yprime c works from the UNIX shell prompt but does not work from the MATLAB prompt y
29. 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 e Unshaded blocks are MATLAB Compiler generated code EA NI est fos ote tie Stand Alone l Dotted block s are C C compiler generated C Application executable Figure 4 2 Building Two M Files into a Stand Alone C Application 4 38 Coding with M Files Only For C code add L cpp to the previous commands and use a C compiler instead of a C compiler 4 39 4 Stand Alone Applications Alternative Ways of Compiling M Files The previous section showed how to compile main m and mrank m separately This section explores two other ways of compiling M files Note These two alternative ways of compiling M files apply to C as well as to C code the only difference is that you add L cpp for C Compiling MATLAB Provided M Files Separately The M file mrank m contains a call to rank The MATLAB Compiler translates the call to rank into a C call to mlfRank The mlfRank routine is part of the MATLAB M File Math Library The mlfRank routine behaves in stand alone applications exactly as the rank function behaves in the MATLAB interpreter However if this default behavior is not desirable you can create your own versi
30. Simple Example The Sierpinski Gasket Consider an M file function called gasket m function thelmage gasket numPoints GASKET An image of a Sierpinski Gasket IM GASKET NUMPOINTS o ge o Example X gasket 50000 imagesc x colormap 1 1 1 0 O 0 axis equal tight o ge o o Copyright c 1984 98 by The MathWorks Inc Revision 1 1 Date 1998 09 11 20 05 06 o thelmage zeros 1000 1000 corners 866 1 1 500 866 1000 startPoint 866 1 theRand rand numPoints 1 theRand ceil theRand 3 for i 1 numPoints startPoint floor corners theRand i theImage startPoint 1 startPoint 2 end startPoint 2 1 J How the Function Works This function determines the coordinates of a Sierpinski Gasket using an Iterated Function System algorithm The function starts with three points that define a triangle and starting at one of these points chooses one of the remaining points at random A dot is placed at the midpoint of these two points From the new point a dot is placed at the midpoint between the new point and a point randomly selected from the original points This process continues and eventually leads to an approximation of a curve A Simple Exampl The Sierpinski Gasket The curve can be graphed in many ways Sierpinski s method is Start with a triangle and from it remove a triangle that is one half the height of the original and inverted This leaves
31. Simulink S function Translates M code to C C code Specifies output stage Specifies number of inputs for Simulink S function Verbose Displays compilation steps option array_indexing fold_mxarrays fold_non_scalar_mxarrays fold_scalar_mxarrays optimize conditionals optimize integer for loops percolate simple types speculate Equivalent to W main L Cpp t T link exe h libmmfile mlib Equivalent to W simulink L C t T link mex libmatlbmx mlib target codegen compile bin link bin where bin mex exe lib mcc Table A 1 mcc Quick Reference Continued Option Description Comment Options w option Displays warning messages option list level level string where level disable enable error No w option displays only serious warnings default W type Controls the generation of type mex function wrappers main simulink lib string com compnm clnm mj mn comhg compnm clnm mj mn excel compnm clnm mj mn excelhg compnm clnm mj mn x Macro to generate Equivalent to MEX function W mex L C t T link mexlibrary libmatlbmx mlib y number Specifies number of outputs Y licensefile z path for Simulink S function Uses licensefile when checking out a Compiler license Specifies path for library and include files Displays help message A maize Compiler Quick Reference A 8 Error and Warning Messages This appendix lists and describes error messa
32. This function calls the C mgasket function The function mlfGasket contains the normal interface for the gasket M function from file lt matlab gt extern examples compiler gasket m lines 1 23 This function processes any input arguments and passes them to the implementation version of the function appearing above mxArray mlfGasket mxArray numPoints int nargout 1 Input Argument Processing mxArray theImage NULL mlfEnterNewContext O 1 numPoints Call M Function j theImage Mgasket nargout numPoints PO SoS a tice Seite Output Argument Processing mlfRestorePreviousContext 0 1 numPoints return mlfReturnValue theImage mlfNF Interface Function The Compiler produces this interface function only when the M function uses the variable nargout The nargout interface allows you to specify the number of requested outputs via the int nargout argument as opposed to the normal interface that dynamically calculates the number of outputs based on the number of non NULL inputs it receives 5 13 5 Controlling Code Generation This is the corresponding m1fNF interface function m1fNFoo for the foo m example described earlier in this chapter This function calls the Mfoo function that appears in foo c The function mlfNFoo contains the nargout interface for the foo M function from file
33. This simple method of creating MEX files works for the majority of users It uses your installed C or C compiler as your default compiler for creating your MEX files If you are a user who does not need to change compilers or you do not need to modify your compiler options files you can skip ahead in this section to Creating MEX Files on page 2 22 Note On Windows 98 systems if you get the error out of environment space see Out of Environment Space Running mex or mbuild on page 2 25 for more information Systems with More than One C C Compiler On systems where there is more than one C or C compiler the mex utility lets you select which of the compilers you want to use Once you choose your C or C compiler that compiler becomes your default compiler and you no longer have to select one when you compile MEX files For example if your system has both the Borland and Watcom compilers when you enter for the first time mex filename c you are asked to select which compiler to use mex has detected the following compilers on your machine 2 19 2 installation and Configuration 2 20 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 D
34. V2 0 option For more information about Compiler options see MATLAB Compiler Option Flags on page 7 31 Warning The specified private directory is not unique Both directoryname1 and directoryname2 are found on the path for this private directory duplicate private directories The Compiler cannot distinguish which private function to use For more information see Compiling Private and Method Functions on page 5 5 B Eror and Warning Messages Run Time Errors Note The error messages described in this section are generated by the Compiler into the code exactly as they are written but are not the only source of run time errors You also can receive run time errors can from the C C Math Libraries these errors are not documented in this book Math Library errors do not include the source file and line number information If you receive such an error and are not certain if it is coming from the C C Math Libraries or your M code compile with the A debugline on option to get additional information about which part of the M source code is causing the error For more information about A the annotation option see MATLAB Compiler Option Flags on page 7 31 Run time Error File filename Line Column The call to function functionname that appeared on this line was not a known function at compile time The function was not found at compile time Run time Error File filename Line Column The call to
35. a value other than a real scalar mbrealscalar issues an error message and halts execution of the MEX file mbrealscalar tells the MATLAB interpreter to check whether x holds a real scalar value If x does not mbrealscalar issues an error message and halts execution of the M file The MATLAB interpreter does not use mbrealscalar to impute x Note that mbrealscalar only tests x at the point in an M file or MEX file where an mbrealscalar call appears In other words an mbrealscalar call tests the value of x only once If x becomes a vector after the mbrealscalar test mbrealscalar cannot issue an error message mbrealscalar defines a real scalar as any value that meets the criteria of both mbreal and mbscalar This code in MATLAB causes mbrealscalar to generate an error message because although n contains only real numbers n is not a scalar n 17 2 15 3 mbrealscalar n Error using gt mbscalar Argument of mbscalar must be scalar mbreal mbscalar mbrealvector mce mbrealvector Purpose Syntax Description Example See Also Assert variable is a real vector mbrealvector n The statement mbrealvector x causes the MATLAB Compiler to impute that x is a real vector At run time if mbrealvector determines that x holds a value other than a real vector mbrealvector issues an error message and halts execution of the MEX file mbrealvector tells the MATLAB interpreter to check whether x holds a real v
36. alone application is to write all the source code in one or more M files or MEX files Coding an application in M files allows you to take advantage of the MATLAB interpretive development environment Then after getting the M file version of your program working properly compile the code and build it into a stand alone application Note It is good practice to avoid manually modifying the C or C code that the MATLAB Compiler generates If the generated C or C code is not to your liking modify the M file and or the compiler options and then recompile If you do edit the generated C or C code remember that your changes will be erased the next time you recompile the M file For more information see Compiling MATLAB Provided M Files Separately on page 4 40 and Interfacing M Code to C C Code on page 5 46 Consider a very simple application whose source code consists of two M files mrank m and main m This example involves C code you use a similar process described below for C code In this example the liner zeros n 1 preallocates memory to help the performance of the Compiler mrank m returns a vector of integers r Each element of r represents the rank of a magic square For example after the function completes r 3 contains the rank of a 3 by 3 magic square function r mrank n r zeros n 1 for k 1 n r k rank magic k end main m contains a main routine that calls mrank and then print
37. and how the Compiler behaves Table 7 4 Compiler Option Categories shows the categories of options Table 7 4 Compiler Option Categories Category Purpose Macros The macro options simplify the compilation process by combining the most common compilation tasks into single options Code Generation These options affect the actual code that the Compiler generates For example L specifies the target language as either C or C Compiler and Environment These options provide information to the Compiler such as where to put d and find I particular files mbuild mex These options provide information for the mbuild and or mex scripts The remainder of this reference page is subdivided into sections that correspond to the Compiler option categories Each section provides a full description of all of the options in the category Macro Options The macro options provide a simplified way to accomplish basic compilation tasks g Debug This option is a macro that is equivalent to G A debugline on 0 none or B macro_option_g 7 31 mcc 7 32 In addition to the G option the g option includes the A debugline on option This will have an impact on performance of the generated code If you want to have debugging information but do not want the performance degradation associated with the debug line information use g A debugline off The g option also includes the O none option causing all comp
38. and pass them to the implementation version of the function Note In C the m1xF interface functions are also C functions in order to allow the feval interface to be uniform between C and C mlxF Interface Function The Compiler always generates the m1xF interface function which is used by feval At times the Compiler needs to use feval to perform argument matching even if the user does not specifically call feval For example X cell 1 5 y 1 2 3 4 5 X deal y would use the feval interface The following C code is the corresponding feval interface m1xGasket 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 lt matlab gt extern examples compiler gasket m lines 1 23 The feval function calls the implementation version of gasket through this function This function processes any input arguments and passes them to the implementation version of the function appearing above void mlxGasket int nlhs mxArray plhs int nrhs mxArray prhs MW BEGIN MLX ofp erage ss a Input Argument Processing mwArray mprhs 1 mwArray mplhs 1 Internal Interface Functions int i mclCppUndefineArrays 1 mplhs if nlhs gt 1 error mwVarargin mwArray Run time Error File gasket Line 1 Column 1 The function g
39. compiler on all UNIX platforms except Linux The GNU C compiler g on Linux UNIX Workstation Note For a list of all the compilers supported by MATLAB see the MathWorks Technical Support Department s Technical Notes at http www mathworks com support tech notes 1600 1601 shtm1 Known Compiler Limitations There are several known restrictions regarding the use of supported compilers The SGI C compiler does not handle denormalized floating point values correctly Denormalized floating point numbers are numbers that are greater than 0 and less than the value of DBL_MIN in the compiler s float h file Due to a limitation of the GNU C compiler g on Linux try catch end blocks do not work The A debugline on option does not work on the GNU C compiler g on Linux because it uses try catch end Some UNIX compilers produce warnings that suggest additional optimizations can be performed that might result in faster code For example on IBM RS 6000 systems you may see a warning message similar to 1500 030 I INFORMATION Miofun_private_imgifinfo Additional optimization may be attained by recompiling and specifying MAXMEM option with a value greater than 2048 See your vendor compiler documentation for more information on how to improve optimization Normally this involves changing compiler options Use CFLAGS in your mbuildopts file Note This compiler warning is benign and will have no har
40. create the corresponding Simulink S function using dynamically sized inputs and outputs use mcc S mymfile The S option is equivalent to the series of options W simulink L C t T link mex libmatlbmx mlib or B macro option s x MEX Function Produce a MEX function For example to translate an M file named mymfile minto C and to create the corresponding MEX file that can be called directly from MATLAB use mcc x mymfile The x option is equivalent to the series of options W mex L C t T link mexlibrary libmatlbmx mlib or B macro option x Bundle Files B ccom C COM Objed Produce a C COM object The B ccom option is equivalent to the series of options t W com component name class name version T link lib h libmmfile mlib i B cexcel C Excel COM Object Produce a C Excel COM object The B cexcel option is equivalent to the series of options B excel component name class name version T link lib h libmmfile mlib b i B csglcom C Handle Graphics COM Object Produce a C COM object that uses Handle Graphics The B csglcom option is equivalent to the series of options 7 33 mcc 7 34 B sgl t W comhg component name class name version T link lib h libmmfile mlib i B csglexcel C Handle Graphics Excel COM Object Produce a C Excel COM object that uses Handle Graphics The B csglexcel option is equivalent to the series of options B sgl t W exc
41. directory in which they installed the MATLAB Compiler Run Time Libraries 4 29 4 Stand Alone Applications Building Shared Libraries 4 30 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 You can include comments in your code by beginning a line first column with 4 ora mbuild treats these lines as comments and ignores them mbuild merges multiple exports files into one master exports list For example given file1 exports as times2 times3 and filei c as int times2 int x return 2 x int times3 int x return 3 x The command mbuild file1 c file1 exports creates a shared library named file1 ext where ext is the platform dependent shared library extension For example on the PC it would be called file1 d11 The shared library exports the symbols times2 and times3 Building COM Objects Building COM Objects Note To create COM components from the MATLAB Compiler you must have the MATLAB COM Builder installed on your system You can use mbuild to create Component Object Model COM objects from MATLAB M files The collection of M
42. function functionname on this line passed quantity inputs and the function is declared with quantity2 There is an inconsistency between the formal and actual number of inputs to a function Run time Error File filename Line Column The call to function functionname on this line requested quantity outputs and the function is declared with quantity2 There is an inconsistency between the formal and actual number of outputs from a function Run time Error File filename Line Column The clear statement did not specifically list the names of variables to be cleared as constant strings Use one of the forms of the clear command that contains the names of the variables to be cleared for example clear name Run time Error File filename Line Column The Compiler does not support EVAL or INPUT functions Currently these are unsupported functions Run time Error File filename Line Column The function functionname was called with more than the declared number of inputs quantity1 There is an inconsistency between the declared number of formal inputs and the actual number of inputs Run Time Errors Run time Error File filename Line Column The function functionname was called with more than the declared number of outputs quantity 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 sta
43. function this example uses the system s compiler as your default compiler for creating your stand alone application If you are a user who does not need to change C or C compilers or you do not need to modify your compiler options files you can skip ahead in this section to Verifying mbuild on page 4 11 If you need to know how to change the options file or select a different compiler continue with this section Changing Compilers Changing the Default Compiler You need to use the setup option if you want to change any options or link against different libraries At the UNIX prompt type mbuild setup Building Stand Alone Applications on UNIX The setup option creates a user specific options file for your ANSI C or C compiler Executing mbuild setup presents a list of options files currently included in the bin subdirectory of MATLAB mbuild setup Using the mbuild setup command selects an options file that is placed in matlab R13 and used by default for mbuild An options file in the current working directory or specified on the command line overrides the default options file in matlab R13 Options files control which compiler to use the compiler and link command options and the runtime libraries to link against To override the default options file use the mbuild f command see mbuild help for more information The options files available for mbuild are 1 matlab bin mbuildopts sh Bu
44. 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 Method functions are implementations specific to a particular MATLAB type or user defined object Method functions are only invoked when the argument list contains an object of the correct class In order to compile a method function you must specify the name ofthe method along with the classname so that the Compiler can differentiate the method function from a nonmethod normal function Note Although MATLAB Compiler 3 0 can currently compile method functions it does not support overloading of methods as implemented in MATLAB This feature is provided in anticipation of support of overloaded methods being added Method directories can contain private directories Private functions are found only when executing a method from the parent method directory Taking all of this into account the Compiler command line needs to be able to differentiate between these various functions that have the same name file called foo m that contains a function called foo can appear in all of these locations at the same time The conventions used on the Compiler
45. gt must be the full pathname to the desired options file Using the f option tells the mex script to use the specified options file for the current execution of mex only it does not reset the default compiler Creating MEX Files The lt matlab gt extern examples mex directory contains C source code for the example yprime c To verify that your system can create MEX files enter at the MATLAB prompt cd matlabroot extern examples mex mex yprime c This should create the yprime d11 MEX file MEX files created on Windows always have the extension dll You can now call yprime as if it were an M function For example yprime 1 1 4 ans 2 0000 8 9685 4 0000 1 0947 If you encounter problems generating the MEX file or getting the correct results refer to External Interfaces API in the MATLAB documentation for additional information about MEX files MATLAB Add In for Visual Studio The MathWorks provides a MATLAB add in for the Visual Studio development system that lets you work easily within the Microsoft Visual C C MSVC environment to create and debug MEX files The MATLAB add in for Visual Studio is included with MATLAB and is automatically installed when you run Microsoft Windows on PCs mex setup and select Microsoft Visual C C version 5 or 6 For more information about the add in see Using an Integrated Development Environment on page 4 23 Note The MATLAB add in for Visual Studio does not curre
46. initialization and termination functions as well as global variable definitions If the functions are not specified in this manner undefined symbols will be produced at link time or run time crashes may occur 7 40 mcc y Number of Outputs Provide more control over the number of valid outputs for your Simulink S function This option specifically sets the number of outputs y for your function If y is omitted the output will be dynamically sized Use this with the S option Compiler and Environment Options b Visual Basic File Generate a Visual Basic file bas that contains the Microsoft Excel Formula Function interface to the Compiler generated COM object When imported into the workbook Visual Basic code this code allows the MATLAB function to be seen as a cell formula function B lt filename gt lt a1 gt lt a2 gt lt an gt Bundle of Compiler Settings Replace B lt filename gt lt a1 gt lt a2 gt lt an gt 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 A bundle file can include replacement parameters for Compiler options that accept names and version numbers For example there is a bundle file for C shared libraries csharedlib that consists of t W lib 1 T link lib h libmmfile mlib To invoke the Compiler to pr
47. 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 a new licensing scheme has been employed that enables the product to be simpler and more user friendly In versions prior to 1 2 1 you could not run the MATLAB Compiler unless you were running MATLAB On networked systems this meant that one user would be holding the license for one copy of MATLAB and the Compiler simultaneously In effect one user required both products and tied up both licenses until the user exited MATLAB Although you can still run the Compiler from within MATLAB it is not required One user could be running the Compiler while another user could be using MATLAB The licensing model is based on how you run the Compiler From the MATLAB command prompt From a DOS UNIX shell Running Compiler from MATLAB When you run the Compiler from inside of MATLAB that is you run mcc from the MATLAB command prompt you hold the Compiler license as long as MATLAB remains open To give up the Compiler license exit MATLAB Introducing the MATLAB Compiler 1 8 Running Compiler from DOS UNIX Shell If you run the Compiler from a DOS or UNIX shell you are runni
48. interpretable as a number B 9 B Eror and Warning Messages Error Unknown annotation option optionname An invalid string was specified after the A option For a complete list of the valid annotation options see MATLAB Compiler Option Flags on page 7 31 or type mcc at the command prompt Error Unknown typesetting option optionname The valid typesetting options available with F are expression indent n list page width and statement indent n Error Unknown warning enable disable string warningstring 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 11 Error Unrecognized option option The option is not one of the valid options for this version of the Compiler See MATLAB Compiler Option Flags on page 7 31 for a complete list of valid options for MATLAB Compiler 3 0 or type mcc at the command prompt Error Use V2 0 to specify desired version You specified V without a version number You must use V2 0 if you specify a version number Error versionnumber is not a valid version number Use V2 0 If you specify a Compiler version number it must be V2 0 The default is V2 0 Warning Messages Warning Messages This section lists the warning messages that the MATLAB Compiler can generate Using the w option for mcc you can control which messages are displayed Each warning message contains a d
49. lt matlab gt extern examples compiler foo m lines 1 8 This interface is only produced if the M function uses the special variable nargout The nargout interface allows the number of requested outputs to be specified via the nargout argument as opposed to the normal interface which dynamically calculates the number of outputs based on the number of non NULL inputs it peceives This function processes any input arguments and passes them to the implementation version of the function appearing above KI mxArray mlfNFoo int nargout mxArray b mxArray x mxArray y Input Argument Processing mxArray a NULL mxArray b NULL mlfEnterNewContext 1 2 b x y Call M Function a Mfoo amp b nargout x y Output Argument Processing mlfRestorePreviousContext 1 2 b x y if b NULL mclCopyOutputArg b b_ else mxDestroyArray b__ return mlfReturnValue a 5 14 Internal Interface Functions mlfVF Interface Function The Compiler produces this interface function only when the M function uses the variable nargout and has at least one output This void interface function specifies zero output arguments to the implementation version of the function and in the event that the implementation version still returns an output which in MATLAB would be assigned to the
50. manually grouping several options together to perform a particular type of compilation you can use one simple option to quickly accomplish basic compilation tasks Note Macro options are intended to simplify the more common compilation tasks You can always use individual options to customize the compilation process to satisfy your particular needs For detailed information about the macros included with the MATLAB Compiler as well as complete information on all the other available Compiler options see the mcc reference page Generating Simulink S Functions Generating Simulink S Functions You can use the MATLAB Compiler to generate Simulink C MEX S functions This allows you to speed up Simulink models that contain MATLAB M code that is referenced from a MATLAB Fen block Note Only the MATLAB Fcn block is supported For more information about Simulink in general see the Simulink documentation For more information about Simulink S functions see Writing S Functions in the Simulink documentation Simulink Specific Options By using Simulink specific options with the MATLAB Compiler you can generate an S function that is compatible with the S Function block The Simulink specific options are S u and y Using any of these options with the MATLAB Compiler causes it to generate code that is compatible with Simulink Using the S Option The simplest S function that the MATLAB Compiler can generate is one wi
51. mbscalar only tests x at the point in an M file or MEX file where an mbscalar call appears In other words an mbscalar call tests the value of x only once If x becomes nonscalar after the mbscalar test mbscalar cannot issue an error message mbscalar defines a scalar as a matrix whose dimensions are 1 by 1 This code in MATLAB causes mbscalar to generate an error message because n does not hold a scalar n 1 2 3 mbscalar n Error using gt mbscalar Argument of mbscalar must be scalar mbint mbintscalar mbintvector mbreal mbrealscalar mbrealvector mbvector mcc mbvector Purpose Assert variable is vector Syntax mbvector n Description The statement mbvector x causes the MATLAB Compiler to impute that x is a vector At run time if mbvector determines that x holds a nonvector value mbvector issues an error message and halts execution of the MEX file mbvector causes the MATLAB interpreter to check whether x holds a vector value If x does not mbvector issues an error message and halts execution of the M file The MATLAB interpreter does not use mbvector to impute x Note that mbvector only tests x at the point in an M file or MEX file where an mbvector call appears In other words an mbvector call tests the value of x only once If x becomes a nonvector after the mbvector test mbvector cannot issue an error message mbvector defines a vector as any matrix whose dimensions are 1 by n or n by 1
52. mbuild uses the C compiler and the MATLAB C Math Library f mbuild cannot deduce from the file extensions whether to compile in C or C mbuild invokes the C compiler 4 Stand Alone Applications 4 16 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 Locating Options Files To locate your options file the mbuild script searches the following The current directory The user profile directory For more information about this directory see The User Profile Directory Under Windows on page 2 16 mbuild uses the first occurrence of the options file it finds If no options file is found mbuild searches your machine for a supported C compiler and uses the factory default options file for that compiler If multiple compilers are found you are prompted to select one Preparing to Compile Compiler Restrictions Some of the supported PC compilers have restrictions regarding their use with the MATLAB Compiler Refer to Supported ANSI C and C PC Compilers on page 2 14 for important limitation information on the supported compilers Other restrictions include Watcom 10 6 and 11 0 are not supported for building stand alone applications The Lec C compiler does not support C The only compilers that support the buildin
53. mlfScalar 1 mclVa numPoints numPoints NULL mclForNext amp viter__ amp i startPoint floor corners theRand i startPoint 2 mciMline 21 mlfAssign amp startPoint mlfFloor mclMrdivide mciPlus mlfIndexRef mclVv corners corners 2 2 mlfIndexRef mclVv theRand theRand mclVv i i mlfCreateColonIndex mclVv startPoint startPoint mlfScalar 2 Page Width 40 This example specifies a page width of 40 mcc xg F page width 40 gasket The segment of generated code is 0 1 2 3 4 5 6 7 8 12345678901 23456789012345678901 2345678901 234567890 1234567890 12345678901234567890 mc1lMline 13 mlfAssign amp thelmage mlfzeros mlfScalar 1000 mlfScalar 1000 5 36 Formatting Compiler Generated Cod NULL des corners 866 1 1 500 866 1000 mclMline 15 mlfAssign amp corners mlfDoubleMatrix 3 2 arrayO double NULL startPoint 866 1 mclMline 16 mlfAssign amp startPoint mlfDoubleMatrix 1 2 array double NULL theRand rand numPoints 1 mclMline 17 mlfAssign amp theRand m1fNRand 1 mclVa numPoints numPoints mlfScalar 1 NULL Setting Indentation Spacing Use the statement indent n option to set the indentation of all statements to n an integer The default is 4 spaces of indentation To set the indentation for expressions use expressi
54. mlib Files on page 5 26 Additional Data Type Support Integer Data Types The signed and unsigned integer arrays int8 int16 int32 uint8 uint16 and uint32 are now supported which provides improved support for the Image Processing Toolbox Function Handles A function handle is a new MATLAB data type that captures all the information about a function that MATLAB needs to evaluate it The MATLAB Compiler supports function handles For more information on function handles see the function handle reference page Improved Support for load and save load and save are now supported when they do not list the variables to be loaded or saved They work by loading or saving all variables that are defined or used within the function Dynamically Linking in MEX Files in the Stand Alone Environment Specifying h or providing the name of a function on the command line will automatically link in any referenced MEX files MATLAB Add In for Visual Studio This add in integrates the MATLAB Compiler into Visual C C Version 5 or 6 To learn more about the MATLAB add in for Visual Studio see Using an Integrated Development Environment on page 4 23 New Features Faster C C Math Library Applications The improved performance of the C C Math Library is due in part to the added scalar accelerated versions of many of the library functions Additional Language Support pause and continue These commands are now supported eval and
55. of M files MEX files and C or C source code files The MATLAB Compiler translates input M files into C source code suitable for your own stand alone applications After compiling this C source code the resulting object file is linked with the object libraries Differences Between MEX iles and Stand Alone Applications For more information about distributing a C application see Distributing Stand Alone Applications on page 4 27 Note If you attempt to compile M files to produce stand alone applications and you do not have the MATLAB C C Math Library installed the system will not be able to find the appropriate libraries and the linking will fail Also if you do not have the MATLAB C C Graphics Library installed the MATLAB Compiler will generate run time errors if the graphics functions are called Stand Alone C Applications To build stand alone C applications MATLAB the MATLAB Compiler a C compiler and the MATLAB C C Math Library must be installed on your system The source code for a stand alone C application consists either entirely of M files or some combination of M files MEX files and C or C source code files The MATLAB Compiler when invoked with the appropriate option flag p or L Cpp translates input M files into C source code suitable for your own stand alone applications After compiling this C source code the resulting object files are linked against the MATLAB C C Math L
56. operator to index into a function Error File filename Line Column Indexing expressions cannot return multiple results There is an assignment in which the left hand side takes multiple values but the right hand side is not a function call but rather a structure access For example x y f z Correct x y f z Incorrect Error File filename Line Column Invalid multiple left hand side assignment For example you try to assign to constants sin 1 Incorrect Error File filename Line Column MATLAB assignment cannot be nested You cannot use a syntax such as x y 2 Usey 2 x y instead Error File filename Line Column Missing operator comma or semicolon There is a syntax error in the file Syntactically an operator a comma or a semicolon is expected but is missing For example if x y z w end Correct if x y z w end Incorrect Compile Time Errors Error File filename Line Column Missing variable or function An illegal name was used for a variable or function For example x Correct x Incorrect Error File filename Line Column Only functions can return multiple values In this example foo must be a function it cannot be a variable a b foo Error File filename Line Column string1 expected string2 found There is a syntax error in the specified line See the online MATLAB Function Reference pages accessible f
57. requirements Microsoft Windows 2 13 UNIX 2 4 T T option flag 7 44 t option flag 5 21 7 44 target language L option flag 7 38 1 9 Index templates requirement 4 6 translate M to C t option flag 7 44 troubleshooting Compiler problems 2 27 4 35 mbuild problems 4 33 MEX file problems 2 25 missing functions 1 20 starting stand alone graphics applications 4 28 U u option flag 3 8 7 39 uicontrol objects 1 21 uimenu objects 1 21 UNIX building stand alone applications 4 7 Compiler installation 2 4 options file 2 6 running stand alone application 4 12 supported compilers 2 4 system requirements 2 4 UNIX compiler limitations 2 5 unsupported functions in stand alone mode 1 19 upgrading from Compiler 1 0 1 1 1 17 from Compiler 2 0 2 1 2 2 2 3 1 17 user profile directory 2 16 V v option flag 7 46 verbose compiler output 7 46 Visual Basic file generating 7 41 Visual Studio add in 4 23 void interface function 5 15 5 20 W W option flag 7 39 w option flag 7 46 warning message Compiler B 1 warnings in compiler output 7 46 watiicopts bat 2 16 Watcom environment variable 2 26 watcopts bat 2 16 Windows See Microsoft Windows wrapper C shared library 5 24 C library 5 28 COM component 5 29 main 5 22 MEX 5 22 Simulink S function 5 24 wrapper file 1 9 MEX 1 9 target types 1 15 wrapper function 5 21 X x option flag 7 33 Y Y option flag 7 47 y option flag 3 8 7 41 Z z option f
58. that the performance of the generated C C code may be faster than the performance of the M code in the MATLAB interpreter Table 7 9 Optimization Options shows the available options Table 7 9 Optimization Options Option Description 0 list Lists all available optimizations 0 all Turns on all optimizations a11 is the default Equivalent to B opt bundle all 7 38 mcc Table 7 9 Optimization Options Continued Option Description 0 none Turns off all optimizations Equivalent to B opt bundle none O opt option gt on off Enables or disables individual optimizations where opt option is array indexing fold mxarrays fold non scalar mxarrays fold scalar mxarrays optimize conditionals optimize integer for loops percolate simple types speculate u Number of Inputs Provide more control over the number of valid inputs for your Simulink S function This option specifically sets the number of inputs u for your function If u is omitted the input will be dynamically sized Use this with the S option W type Function Wrapper Control the generation of function wrappers for a collection of Compiler generated M files You provide a list of functions and the Compiler generates the wrapper functions and any appropriate global variable definitions Table 7 10 Function Wrapper Types shows the valid options Table 7 10 Function Wrapper Types
59. three triangles From each of the remaining three triangles remove a triangle that is one fourth the height of these new triangles and inverted This leaves nine triangles The process continues and at infinity the surface area becomes zero and the length of the curve is infinite To achieve a reasonable approximation of the Sierpinski Gasket set the number of points to 50 000 To invoke the M file and compute the coordinates you can use X 7 gasket 50000 To display the figure you can use imagesc x colormap 1 1 1 0 O 0 axis equal tight Compiling the M File into a MEX File To create a MEX file from this M file enter the mcc command at the MATLAB interpreter prompt mcc x gasket This mcc command generates A file named gasket c containing MEX file C source code A file named gasket h containing the public information A file named gasket mex c containing the MEX function interface MEX wrapper e A MEX file named gasket mex The actual filename extension of the executable MEX file varies depending on your platform e g on the PC the file is named gasket d11 mcc automatically invokes mex to create gasket mex from gasket c and gasket mex c The mex utility encapsulates the appropriate C compiler and linker options for your system 3 Working with MEX Files This example uses the x macro option to create the MEX file For more information on this Compiler option see the mcc reference page
60. to mbvector must be a vector mbint mbvector mbintscalar mcc mbreal Purpose Syntax Description Example See Also Assert variable is real mbreal n The statement mbreal x causes the MATLAB Compiler to impute that x is real not complex At run time if moreal determines that x holds a complex value mbreal issues an error message and halts execution of the MEX file mbreal tells the MATLAB interpreter to check whether x holds a real value If x does not mbreal issues an error message and halts execution of the M file The MATLAB interpreter does not use mbreal to impute x Note that mbreal only tests x at the point in an M file or MEX file where an mbreal call appears In other words an mbreal call tests the value of x only once If x becomes complex after the mbreal test mbreal cannot issue an error message A real value is any scalar vector or matrix that contains no imaginary components This code in MATLAB causes mbreal to generate an error message because n contains an imaginary component n 17 5i mbreal n Error using gt mbreal Argument to mbreal must be real mbrealscalar mbrealvector mcc 7 15 mbrealscalar Purpose Syntax Description Example See Also 7 16 Assert variable is real scalar mbrealscalar n The statement mbrealscalar x causes the MATLAB Compiler to impute that x is a real scalar At run time if mbrealscalar determines that x holds
61. you select which of the compilers you want to use Once you choose your C or C compiler that compiler becomes your default compiler and you no longer have to select one when you compile your stand alone applications For example if your system has both the Lcc and Microsoft Visual C C compilers when you enter for the first time mbuild filename c you are asked to select which compiler to use Please choose your compiler for building stand alone MATLAB applications Select a compiler 4 17 4 Stand Alone Applications 1 Lcc version 2 4 in D Applications Mathworks sys lcc 2 Microsoft Visual C C version 6 0 in D Applications Microsoft Visual Studio 0 None Compiler Select the desired compiler by entering its number and pressing Return You are then asked to verify your information Changing Compilers Changing the Default Compiler To change your default C or C compiler you select a different options file You can do this at anytime by using the setup command This example shows the process of changing your default compiler to the Microsoft Visual C C Version 6 0 compiler mbuild setup Please choose your compiler for building stand alone MATLAB applications Would you like mbuild to locate installed compilers y n n Select a compiler 1 Borland C Builder version 2 Borland C Builder version 93 Borland C Builder version 4 Borland C Builder version 5 Borland C C versi
62. 2 Dynamic Link Libraries Before running a stand alone application you must ensure that the directory containing the DLLs is on your path The directory must be on your operating system PATH environment variable On Windows NT use the Control Panel to set the value Running Your Application You can now run your stand alone application by launching it from the DOS command line For example ex1 ans 1 3 5 2 4 6 ans Building Stand Alone Applications on PCs 1 0000 7 0000i 4 0000 10 0000i 2 0000 8 0000i 5 0000 11 0000i 3 0000 9 0000i 6 0000 12 0000i Verifying the MATLAB Compiler There is MATLAB code for an example hello m included in the lt matlab gt extern examples compiler directory To verify that the MATLAB Compiler can generate stand alone applications on your system type the following at the MATLAB prompt mcc m hello m This command should complete without errors To run the stand alone application hello invoke it as you would any other Windows console application by typing its name on the MS DOS command line The application should run and display the message Hello World When you execute the mcc command to link files and libraries mcc actually calls the mbuild script to perform the functions 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 mbuil
63. AB Compiler compiling complete syntactic details 7 25 7 49 embedded M file 7 30 getting started 3 1 3 5 compopts bat 2 16 configuration problems 2 25 conflicting options resolving 7 29 conventions in our documentation table xii creating MEX file 3 3 cshrc 4 11 D d option flag 7 43 debugging G option flag 7 47 line numbers of errors 7 38 debugging symbol information 7 31 debugline setting 5 44 Digital Fortran 2 26 Digital UNIX C shared libraries 4 13 Fortran shared libraries 4 13 directory user profile 2 16 DLL See shared library Index duality command function 5 22 E embedded M file 7 30 environment variable 2 26 library path 4 11 out of environment space on Windows 2 25 error messages Compiler B 1 compile time B 2 B 10 internal error B 1 run time B 18 B 19 warnings B 11 B 17 errors getting line numbers of 7 38 Excel plug in building 4 32 executables See wrapper file export list 5 24 exported interfaces including 7 44 S external 5 46 7 5 F F option flag 5 35 7 37 f option flag 7 47 Fen block 3 7 feval 5 48 7 6 interface function 5 11 5 16 feval pragma 7 5 7 6 figure objects 1 21 file license dat 2 6 2 17 mccpath 7 28 mlib 5 24 5 26 wrapper 1 9 fold mxarrays optimization 6 5 fold non scalar mxarrays optimization 6 4 fold scalar mxarrays optimization 6 4 folding 6 4 formatting code 5 35 F option flag 7 37 listing all options 5 35 setting indentation 5 37 setting pa
64. Any Compiler generated stand alone application must be able to locate the C C libraries along the library path environment variable SHLIB PATH LIBPATH or LD LIBRARY PATH in order to 4 Stand Alone Applications be found and loaded Consequently to share a Compiler generated stand alone application with another user you must provide all of the required shared libraries For more information about the required shared libraries for UNIX see Packaging UNIX Applications on page 4 13 Running Your Application To launch your application enter its name on the command line For example ex1 ans 1 3 5 2 4 6 ans 1 0000 7 0000i 4 0000 10 0000i 2 0000 8 0000i 5 0000 11 0000i 3 0000 9 0000i 6 0000 12 0000i Verifying the MATLAB Compiler There is MATLAB code for an example hello m included in the matlab extern examples compiler directory To verify that the MATLAB Compiler can generate stand alone applications on your system type the following at the MATLAB prompt mcc m hello m This command should complete without errors To run the stand alone application hello invoke it as you would any other UNIX application typically by typing its name at the UNIX prompt The application should run and display the message Hello World When you execute the mcc command to link files and libraries mcc actually calls the mbuild script to perform the functions Building Stand Alone Applications on UNIX
65. B Compiler can generate MEX files from the MATLAB command line and from the UNIX or DOS command line Figure 2 1 MATLAB Compiler Installation Sequence for Creating MEX Files shows the Compiler installation sequence for creating MEX files on both platforms The sections following the flowchart provide more specific details for the individual platforms Additional steps may be necessary if you plan to create stand alone applications or libraries however you still must perform the steps given in this chapter first Chapter 4 Stand Alone Applications provides the details about the additional installation and configuration steps necessary for creating stand alone applications and libraries Note This flowchart assumes that MATLAB is properly installed on your system System Configuration for MEXFiles Install MATLAB Compiler Install ANSI C C Compiler Verify mex Use MATLAB installer to install component MATLAB Compiler Is ANSI C or C compiler installed Follow vendor s instructions to install and test ANSI C or C compiler Test your mex configuration Verify MATLAB Does the MATLAB command mex yprime c generate proper MEX file See mex Yes Troubleshooting Compiler can generate MEX files from MATLAB DOS Test your MATLAB Compiler installation configuration UNIX command line
66. C endif include libmatlb h extern void InitializeModule gasket void extern void TerminateModule gasket void extern mexLocalFunctionTable local function table gasket The Generated Header Files extern mxArray mlfGasket mxArray numPoints extern void mlxGasket int nlhs mxArray plhs int nrhs mxArray prhs ifdef X 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 I1 MATLAB Compiler 3 0 Date Wed Jan 23 14 54 22 2002 Arguments B macro default O all O fold scalar mxarrays on 0 fold non scalar mxarrays on 0 optimize integer for loops on O array indexing on O optimize conditionals on t L Cpp T codegen F page width 60 gasket ifndef gasket hpp define X gasket hpp 1 include libmatlb hpp extern void InitializeModule gasket extern void TerminateModule gasket extern mexLocalFunctionTable local function table gasket 5 9 5 Controlling Code Generation extern mwArray gasket mwArray numPoints mwArray DIN ifdef X cplusplus extern C endif void mlxGasket int nlhs mxArray plhs int nrhs mxArray prhs endif 5 10 In
67. C source none No comments or code from the M file are added to code To control the line preprocessor directives that are included in the generated C C source use mcc A line setting Table 7 6 Line Annotation Options shows the available line directive settings Table 7 6 Line Annotation Options Setting 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 1line preprocessor directives to the generated C C source code The default is of f To control if run time error messages report the source file and line number use mcc A debugline on 7 36 mcc Table 7 7 Run Time Error Annotation Options shows the available debugline directive settings Table 7 7 Run Time Error Annotation Options Setting Description on Specifies the presence of source file and line number information in run time error messages off Specifies no source file and line number information in run time error messages The default is off For example to include all of your M code including comments in the generated file and the standard line preprocessor directives use mcc A annotation all A line on or mcc A line on The default is all for code comment inclusion To include none of your M code and no 1ine preprocessor directives use mcc A annotation none A
68. Compiler Verification elslles 2 11 Microsoft Windows on PCs 0 000 c eee 2 13 System Requirements 0 0 0 cece cece ee eee eee 2 13 Installationyssc 420 5 56036 hese binds wd ea Ba ed 2 17 mex Verification 0 ccc eee eens 2 19 MATLAB Compiler Verification 0000 eee 2 23 Troubleshooting 0 0c cece eee eens 2 25 mex Troubleshooting 0 cc cece cence ees 2 25 Troubleshooting the Compiler 0 000 c ee eee 2 27 li Contents Working with MEX Files 3 A Simple Example The Sierpinski Gasket 3 2 Compiling the M File into a MEX File 3 3 Invoking the MEX File 0 cece eee 3 4 Compiler Options and Macros 000000 3 6 Generating Simulink S Functions 3 7 Simulink Specific Options 20 0 0 0 cece eee eee 3 7 Specifying S Function Characteristics 000 3 8 Converting Script M Files to Function M Files 3 10 Stand Alone Applications 4 Differences Between MEX Files and Stand Alone Applications 004 4 2 Stand Alone C Applications 0 0 0 0 eee 4 2 Stand Alone C Applications 0 0 0c cee ee eens 4 3 Building Stand Alone C C Applications 4 4 Overview oc ese dass nek oe Vash ak oad cue neuf Manele eas 4 4 Getting Started clle beat Ale ah Sie ig tee redes
69. EE NEU OR 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 Linker Stand Alone 7 Application Shaded blocks are user written code e Shadowed blocks are tools e Unshaded blocks are MATLAB Compiler generated code Dotted blocks are C C compiler generated code Figure 4 3 Mixing M Files and C Code to Form a Stand Alone Application 4 44 Mixing Miles and C or C mrankp c The code in mrankp c calls mrank and outputs the values that mrank returns MRANKP C Posix C main program illustrating the use of the MATLAB Math Library Calls mlfMrank obtained by using MCC to compile mrank m Revision 1 3 include lt stdio h gt include lt math h gt include matlab h Prototype for mlfMrank extern mxArray mlfMrank mxArray main int argc char argv mxArray N Matrix containing n mxArray R Result matrix int n Integer parameter from command line Get any command line parameter if argc gt 2 n atoi argv 1 else n 12 PkgInitialize Initialize the library of M Functions Create a 1 by 1 matrix containing n N mlfScalar n Call mlfMrank the compiled version of mrank m R mlifMrank N 4 45 4 Stand
70. I lt directory1 gt I lt directory2 gt 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 lt outputfile gt Specify the basename of the final executable output stand alone applications only of the Compiler A suitable possibly platform dependent extension is added to the specified basename e g exe for PC stand alone applications Note You cannot use this option to specify a different name for a MEX file t Translate M to C C Translate M files specified on the command line to C C files T lt target gt Output Stage Specify the desired output stage Table 7 11 Output Stage Options gives the possible values of target mcc Table 7 11 Output Stage Options Target Description codegen compile mex compile mexlibrary compile exe compile lib link mex link mexlibrary link exe link lib Translates M files to C C files and generates a wrapper file The default is codegen Same as codegen plus compiles C C files to object form suitable for linking into a Simulink S function MEX file Same as codegen plus compiles C C files to object form suitable for linking into an ordinary non S function MEX file Same as codegen plus compiles C C files to object form suitable for linking into a standalone executable Sa
71. Inc Revision 1 1 Date 1998 09 11 20 05 06 o thelmage zeros 1000 1000 corners 866 1 1 500 866 1000 startPoint 866 1 theRand rand numPoints 1 theRand ceil theRand 3 for i 1 numPoints startPoint floor corners theRand i startPoint 2 theImage startPoint 1 startPoint 2 1 J end foo M File function a b foo x y if nargout elseif nargout a X elseif nargout a X 5 2 Code Generation Overview b y end fun M File function a fun b a 1 b 1 b 1 a 2 b 1 b 2 a 3 b 2 4 sample M File function y sample varargin varargin y 0 Generated Code This chapter investigates the generated header files interface functions and wrapper functions for the C MEX stand alone C and C targets and C and C libraries When you use the MATLAB Compiler to compile an M file it generates these files C or C code depending on your target language L specification Header file Wrapper file depending on the W option The C or C code that is generated by the Compiler and the header file are independent of the final target type and target platform That is the C or C code and header file are identical no matter what the desired final output The wrapper file provides the code necessary to support the output executable type So the wrapper file is different for each executable type Table 5 1 Compiler Genera
72. MATLAB Compiler The Language of Technical Computing Computation Visualization 1 Programming 1 User s Guide E v MathWorks Version 3 X Lr How to Contact The MathWorks www mathworks com comp soft sys matlab support mathworks com suggest mathworks com bugs mathworks com doc mathworks com service mathworks com info mathworks com 508 647 7000 508 647 7001 The MathWorks Inc Web Newsgroup Technical support Product enhancement suggestions Bug reports Documentation error reports Order status license renewals passcodes Sales pricing and general information Phone Fax Mail 3 Apple Hill Drive Natick MA 01760 2098 For contact information about worldwide offices see the MathWorks Web site MATLAB Compiler User s Guide COPYRIGHT 1995 2002 by The MathWorks Inc The software described in this document is furnished under a license agreement The software may be used or copied only under the terms of the license agreement No part of this manual may be photocopied or repro duced in any form without prior written consent from The MathWorks Inc FEDERAL ACQUISITION This provision applies to all acquisitions of the Program and Documentation by or for the federal government of the United States By accepting delivery of the Program the government hereby agrees that this software qualifies as commercial computer software within the meaning of FAR Part 12 212 DFARS Part 227 7202 1 DFA
73. RS Part 227 7202 3 DFARS Part 252 227 7013 and DFARS Part 252 227 7014 The terms and conditions of The MathWorks Inc Software License Agreement shall pertain to the government s use and disclosure of the Program and Documentation and shall supersede any conflicting contractual terms or conditions If this license fails to meet the government s minimum needs or is inconsistent in any respect with federal procurement law the government agrees to return the Program and Documentation unused to MathWorks MATLAB Simulink Stateflow Handle Graphics and Real Time Workshop are registered trademarks and TargetBox is a trademark of The MathWorks Inc Other product or brand names are trademarks or registered trademarks of their respective holders Printing History September 1995 First printing March 1997 Second printing January 1998 Third printing Revised for Version 1 2 January 1999 Fourth printing Revised for Version 2 0 Release 11 September 2000 Fifth printing Revised for Version 2 1 Release 12 October 2001 Online only Revised for Version 2 3 July 2002 Sixth printing Revised for Version 3 0 Release 13 Preface Related Products 2 collages kgs ES x Using this Guide unus A pm ERES xi Typographical Conventions lees xii Introducing the MATLAB Compiler 1 Introduction vnencss ieeAoik V apepULEGeGu E EE DRE 1 2 Before You Begin 0 0 ccc ccc eee eens 1 2 New Features
74. Solaris its name is yprime mexsol You can now call yprime from the MATLAB prompt as if it were an M function For example yprime 1 1 4 ans 2 0000 8 9685 4 0000 1 0947 If you encounter problems generating the MEX file or getting the correct results refer to External Interfaces API in the MATLAB documentation for additional information about MEX files UNIX Workstation MATLAB Compiler Verification Verifying from MATLAB Once you have verified that you can generate MEX files on your system you are ready to verify that the MATLAB Compiler is correctly installed Type the following at the MATLAB prompt mcc x invhilb After a short delay this command should complete and display the MATLAB prompt Next at the MATLAB prompt type which invhilb The which command should indicate that invhilbis now a MEX file by listing the filename followed by the appropriate UNIX MEX file extension For example if you run the Compiler on Solaris the Compiler creates the file invhilb mexsol Finally at the MATLAB prompt type invhilb 10 Note that this tests only the Compiler s ability to make MEX files If you want to create stand alone applications refer to Chapter 4 Stand Alone Applications for additional details Verifying from UNIX Command Prompt To verify that the Compiler can generate MEX files from the UNIX command prompt you follow a similar procedure as that used in the previous section Note Before you test t
75. T Profiles username Application Data MathWorks MATLAB R13 mexopts bat is being updated Installing the MATLAB Visual Studio add in Updated If the specified compiler cannot be located you are given the message The default location for compiler name is directory name but that directory does not exist on this machine Use directory name anyway y n Using the setup option sets your default compiler so that the new compiler is used everytime you use the mex script Modifying the Options File Another use of the setup option is if you want to change your options file settings For example if you want to make a change to the current linker settings or you want to disable a particular set of warnings you should use the setup option 2 21 2 installation and Configuration 2 22 The setup option copies the appropriate options file to your user profile directory To make your user specific changes to the options file you edit your copy of the options file in your user profile directory to correspond to your specific needs and save the modified file After completing this process the mex script will use the new options file everytime with your modified settings Temporarily Changing the Compiler To temporarily change your C or C compiler use the f option as in mex f lt file gt The f option tells the mex script to use the options file lt file gt If lt file gt is not in the current directory then lt file
76. Type Description mex Produces a mexFunction interface main Produces a POSIX shell main function simulink Produces a Simulink C MEX S function interface 7 39 mcc Table 7 10 Function Wrapper Types Continued Type Description lib lt string gt com component name class name lt major gt lt minor gt comhg lt component_name gt lt class_ name gt lt major gt lt minor gt excel lt component_name gt lt class_ name gt lt major gt lt minor gt excelhg lt component_name gt lt class_name gt lt major gt lt minor gt none Produces an initialization and termination function for use when compiling this Compiler generated code into a larger application This option also produces a header file containing prototypes for all public functions in all M files specified lt string gt becomes the base file name for the generated C C and header file Creates a exports file that contains all nonstatic function names Produces a COM object from MATLAB M files Produces a Handle Graphics COM object from MATLAB M files Produces a COM object from MATLAB M files Produces a Handle Graphics COM object from MATLAB M files Does not produce a wrapper file The default is none Caution When generating function wrappers you must specify all M files that are being linked together on the command line These files are used to produce the
77. able type For example a MEX wrapper contains the MEX gateway routine that sets up the left and right hand arguments for invoking the Compiler generated code The code produced by the MATLAB Compiler is independent of the final target type MEX executable or library The wrapper file provides the necessary interface to the target type Note MEX files generated by the MATLAB Compiler are not backward compatible Creating MEX Files The MATLAB Compiler when invoked with the x macro option produces a MEX file from M files The Compiler 1 Translates your M code to C code 2 Generates a MEX wrapper 3 Invokes the mex utility which builds the C MEX file source into a MEX file by linking the MEX file with the MEX version of the math libraries libmatlbmx Figure 1 1 Developing MEX Files illustrates the process of producing a MEX file The MATLAB interpreter dynamically loads MEX files as they are needed Introducing the MATLAB Compiler 1 10 M File mcc x C version of M code ij C MEX File Wrapper MEX Math Library libmatlbmx e m MEX File Leo MAAN c XO a WO c Wee and Figure 1 1 Developing MEX Files e Shaded block is user written code Shadowed blocks are MathWorks tools Unshaded blocks are MATLAB Compiler generated code Dotted block is C C compiler generated executable MATLAB users who do not have the MATLAB Compiler must
78. al hpp where file is the name of the initial M file containing the external pragma This header file will contain the extern declaration of the function that the user must provide This function must conform to the same interface as the Compiler generated code For more information on the s external pragma see Interfacing M Code to C C Code on page 5 46 7 5 function Purpose Syntax Description 7 6 feval pragma s function function name list This pragma informs the MATLAB Compiler that the specified function s will be called through an feval eval or Handle Graphics callback You need to specify this pragma only to assist the Compiler in locating and automatically compiling the set of functions when using the h option If you are using the function pragma to define functions that are not available in M code you should use the external pragma to define the function For example s function myfunctionwritteninc This implies that myfunctionwritteninc is an M function that will be called using feval The Compiler will look up this function to determine the correct number of input and output variables Therefore you need to provide a dummy M function that contains a function line and a external pragma such as function y myfunctionwritteninc a b c external The function statement indicates that the function takes three inputs a b c and returns a single output variable y No additi
79. amp b c amp d will not elicit the warning message from the Compiler We recommend that you use parentheses to get the same behavior now and in the future Warning File filename Line Column The MATLAB Compiler does not currently support MATLAB object oriented programming References to the method methodname will produce a run time error matlab method used This warning occurs if the file being compiled references a function that has only a method definition Warning File filename Line Column The save statement cannot be translated unless it specifically lists the names of variables to be saved as constant strings save without constant strings Use one of the forms of the save command that contains the names of the variables to be saved for example save filename num Warning Messages Warning File filename Line Column The second output argument from the functionname function is only available in MEX mode A run time error will occur if this code is executed in stand alone mode unix dos second argument The DOS command can be called with two output arguments That form cannot be compiled in stand alone mode This warning occurs if the DOS command was called with two output arguments in a file that is being compiled in stand alone mode For example r s dos 1s Causes a warning when compiling stand alone Warning File filename Line Column This load save statement referred to variable v
80. ample mcc V2 0 L Cpp Correct mcc V2 0L Cpp Incorrect Error The optionname option requires an argument e g proper example usage You have incorrectly used a Compiler option For more information about Compiler options see MATLAB Compiler Option Flags on page 7 31 or type mcc at the command prompt Error This version of MCC does not support the creation of C MEX code You cannot create C MEX functions with the current Compiler Error Unable to open file filename lt string gt There is a problem with your specified file For example there is no write permission to the output directory or the disk is full Error Unable to set license linger interval error code is errornumber A license manager failure has occurred Contact Technical Support at The MathWorks with the full text of the error message Error Uninterpretable number of inputs set on command line commandline When generating a Simulink S function the inputs specified on the command line was not a number For example mcc S u 2 sample m Correct mcc S u a sample m Incorrect Error Uninterpretable number of outputs set on command line commandline When generating a Simulink S function the outputs specified on the command line was not a number For example mcc S y 2 sample m Correct mcc S y a sample m Incorrect Error Uninterpretable width set on command line commandline The argument to the page width option was not
81. and the wrapper are then passed to the C C compiler which combines them with any user defined C C programs and eventually links them against the appropriate libraries The end result of this sequence is the target as described in the table above Introducing the MATLAB Compiler Why Compile M Files There are several reasons to compile M files To create stand alone applications To create C shared libraries DLLs on Windows or C static libraries To create COM components To hide proprietary algorithms Stand Alone Applications and Libraries You can create MATLAB applications that take advantage of the mathematical functions of MATLAB yet do not require that the user owns MATLAB Stand alone applications are a convenient way to package the power of MATLAB and to distribute a customized application to your users You can develop an algorithm in MATLAB to perform specialized calculations and use the Compiler to create a C shared library DLL on Windows or a C static library You can then integrate the algorithm into a C C application After you compile the C C application you can use the MATLAB algorithm to perform specialized calculations from your program Excel Plug Ins With the optional MATLAB Excel Builder you can automatically generate a Visual Basic Application file bas and a plug in DLL from your MATLAB model that can be imported into Excel as a stand alone function COM Components With t
82. ans variable it deallocates the output This is the corresponding m1fVF interface function m1fVFoo for the foo m example described at the beginning of this section This function calls the C Mfoo implementation function that appears in foo c The function mlfVFoo contains the void interface for the foo M function from file lt matlab gt extern examples compiler foo m lines 1 8 The void interface is only produced if the M function uses the special variable nargout and has at least one output The void interface function specifies zero output arguments to the implementation version of the function and in the event that the implementation version still returns an output which in MATLAB would be assigned to the ans variable it deallocates the output This function processes any input arguments and passes them to the implementation version of the function appearing above void mlfVFoo mxArray x mxArray y E see Input Argument Processing xf mxArray a NULL mxArray b NULL mlfEnterNewContext 0 2 x y Call M Function j a Mfoo amp b O x y Rss scost esos Output Argument Processing mlfRestorePreviousContext 0 2 x y mxDestroyArray a mxDestroyArray b 5 Controlling Code Generation 5 16 C Interface Functions The C interface functions process any input arguments
83. ariablename that was not referenced in the function load save unreferenced This warning occurs if a variable is loaded saved via a load save command but then does not occur elsewhere in scope Warning File filename Line Column Unmatched end end without block The end statement does not have a corresponding for while switch try or if statement Warning File filename Line Column Unrecognized Compiler pragma pragmaname unrecognized_pragma Use one of the Compiler pragmas as described in Chapter 7 Reference Warning File filename Line Column name has been used as both a function and a variable the variable is ignored inconsistent variable When a name represents both a function and a variable it is used as the function only Warning File filename Line Column variablename has not been defined prior to use on this line undefined_variable Variables should be defined prior to use Warning Line Column Function with duplicate name functionname cannot be called duplicate_function_name This warning occurs when an M file contains more than one function with the same name Warning filename is a P file being referenced from filename NOTE A link error will be produced if a call to this function is made from stand alone mode mex_or_p_file The Compiler cannot generate a call to a function in a P file for stand alone code The warning occurs if a call to a function that is de
84. as your default compiler for creating C MEX files 2 installation and Configuration 2 8 If you do not need to change C or C compilers or you do not need to modify your compiler options files you can skip ahead in this section to Creating MEX Files on page 2 9 If you need to know how to change the options file continue with this section Changing Compilers Changing the Default Compiler To change your default C or C compiler you select a different options file You can do this at anytime by using the command mex setup Using the mex setup command selects an options file that is placed in matlab R13 and used by default for mex An options file in the current working directory or specified on the command line overrides the default options file in matlab R13 Options files control which compiler to use the compiler and link command options and the runtime libraries to link against To override the default options file use the mex f command see mex help for more information The options files available for mex are 1 lt matlab gt bin gccopts sh Template Options file for building gcc MEX files 2 lt matlab gt bin mexopts sh Template Options file for building MEX files via the system ANSI compiler Enter the number of the options file to use as your default options file Select the proper options file for your system by entering its number and pressing Return If an options file
85. asket V was called with more than the d eclared number of outputs 1 if nrhs gt 1 error mwVarargin mwArray Run time Error File gasket Line 1 Column 1 The function gasket V was called with more than the d eclared number of inputs 1 for i 0 i lt 1 amp amp i lt nrhs i mprhs i mwArray prhs i 0 for i lt 1 i mprhs i MakeDIN L _ Call M Function mplhs 0 Mgasket nlhs mprhs 0 of ara prigaia sa Output Argument Processing plhs 0 mplhs 0 FreezeData MW END MLX F Interface Function The Compiler always generates the F interface function which contains the normal C interface to the function This code is the corresponding C interface function gasket from the Sierpinski Gasket example This function calls the C code 5 17 5 Controlling Code Generation 5 18 LI LI LI The function gasket contains the normal interface for the gasket M function from file lt matlab gt extern examples compiler gasket m lines 1 23 This function processes any input arguments and passes them to the implementation version of the function appearing above mwArray gasket mwArray numPoints int nargout 1 mwArray theImage mwArray UNDEFINED Call M Function theImage Mgasket nargout numPoint
86. atically you can use the c option for example mcc mc filename Compiler Options Files Options files contain the required compiler and linker settings for your particular C or C compiler The MathWorks provides options files for every supported C or C compiler The options file for UNIX is mbuildopts sh Table 4 3 Compiler Options Files on the PC contains the PC options files Much of the information on options files in this chapter is provided for those users who may need to modify an options file to suit their specific needs Many users never have to be concerned with how the options files work Note If you are developing C applications make sure your C compiler supports the templates features of the C language If it does not you may be unable to use the MATLAB C C Math Library Building Stand Alone Applications on UNIX Building Stand Alone Applications on UNIX This section explains how to compile and link C or C source code into a stand alone UNIX application This section includes Configuring for C or C on page 4 7 Preparing to Compile on page 4 8 Verifying mbuild on page 4 11 Verifying the MATLAB Compiler on page 4 12 About the mbuild Script on page 4 13 Packaging UNIX Applications on page 4 13 Configuring for C or C The mbuild script deduces the type of files you are compiling by the file extension If you include both C and C files mouild uses the C compil
87. ation D 11101 SK ke ct Uses of the Compiler See Chapter 4 Stand Alone Applications for complete details regarding stand alone applications Figure 1 2 Developing a Typical Stand Alone C Application illustrates the process of developing a typical stand alone C application Use the same basic process for developing stand alone C applications but use the p option instead of the m option with the MATLAB Compiler and a C compiler instead of a C compiler Note The MATLAB Compiler contains a tool mbuild which simplifies much of this process Chapter 4 Stand Alone Applications describes the mbuild tool p and m are examples of options that you use to control how the Compiler works Chapter 7 Reference includes a complete description ofthe Compiler options in the mcc section Throughout this book you will see numerous examples of how these options are used with the Compiler to perform various tasks 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 M File s MATLAB Compiler Generated Code Types C Code C Code MAIN UM 2 Ee
88. atlab 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 The Compiler generated MEX file appears in the list as the filename followed by the extension d11 In this example the Compiler creates the file invhilb d11 For more information on which files the Compiler creates for a compilation see Chapter 5 Controlling Code Generation To test the newly created MEX file you would start MATLAB and at the MATLAB prompt you could type invhilb 10 Troubleshooting Troubleshooting This section identifies some of the more common problems that can occur when installing and configuring the MATLAB Compiler mex Troubleshooting Out of Environment Space Running mex or mbuild On Windows 98 systems the mex and mbuild scripts require more than the default amount of environment space If you get the error out of environment space add this line to your config sys file shell c command com e 32768 p On Windows Me systems if you encounter this problem and are using the MATLAB add in for Visual Studio follow the procedure in Configuring on Windows 98 and Windows Me Systems on page 4 25
89. b option is equivalent to the series of options t W lib shared library name T link lib h libmmfile mlib B pcode MATLAB P Code Produce MATLAB P code The B pcode option is equivalent to the series of options t L P B sgl Stand Alone C Graphics Library Produce a stand alone C application that uses Handle Graphics The B sgl option is equivalent to the series of options m W mainhg libmwsglm 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 Code Generation Options A Annotation Control for Output Source Control the type of annotation in the resulting C C source file The types of annotation you can control are e M file code and or comment inclusion annotation e line preprocessor directive inclusion line Whether error messages report the source file and line number debugline To control the M file code that is included in the generated C C source use mcc A annotation type 7 35 mcc Table 7 5 Code Comment Annotation Options shows the available annotation options Table 7 5 Code Comment Annotation Options Type Description all Provides the complete source of the M file interleaved with the generated C C source The default is a11 comments Provides all of the comments from the M file interleaved with the generated C
90. ble for variable lt name gt If lt value gt contains spaces enclose it in single quotes e g CFLAGS opt 1 opt2 The definition def can reference other variables defined in the options file To reference a variable in the options file prepend the variable name with a e g CFLAGS CFLAGS opt2 Override an options file variable for variable name If def contains spaces enclose it in single quotes e g CFLAGS opt1 opt2 The definition def can reference other variables defined in the options file To reference a variable in the options file prepend the variable name with a e g CFLAGS CFLAGS opt2 Note Some of these options f g and v are available on the mcc command line and are passed along to mbuild Others can be passed along using the M option to mcc For details on the M option see the mcc reference page 7 24 mcc Purpose Syntax Description Invoke MATLAB Compiler mcc options mfile1 mfile2 mfileN C C filei C C fileN 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 Command Line Syntax You may specify one or more MATLAB Compiler option flags to mcc Most option flags have a one letter name You can list options separately on the command line for example mcc m g myfun You can group o
91. btimefun is the only parameter being passed If the example had two or more parameters then the quotes would be necessary as in gt gt mcc B cexcel component class 1 0 weekday data tic calendar toc mlib Files Shared libraries like libraries let you compile a common set of functions once and then compile other M functions that depend on them without compiling them again You accomplish this using mlib files which are automatically generated when you generate the shared library Creating an mlib File When you create a library wrapper file you also get a mlib file with the same base name For example mcc W lib libtimefun L C t T link lib h weekday date tic calendar toc creates Supported Executable Types libtimefun c libtimefun h libtimefun exports libtimefun mlib libtimefun ext The last file liobtimefun ext is the shared library file for your platform For example on the PC the shared library is libtimefun dll Using an mlib File This example uses two functions tic and toc that are in the shared library Consider a new function timer defined as function timer tic X fft 1 1000 toc Prior to mlib files if you compiled timer using mcc m timer both tic and toc would be recompiled due to the implicit h option included in the m macro Using mlib files you would use mcc m timer libtimefun mlib At compile time function definitions for tic and toc are located in the libtimefun
92. can generate either C or C code for the compiler M files but the created COM interface will always require C This is a requirement of COM and not particular to the MATLAB Compiler All of the extra files generated by the MATLAB Compiler that are required for producing the COM objects are added to the mbuild command line The details of how mbuild processes the new file types def rc and idl are specified in How mbuild Processes the File Types on page 5 32 If the major and minor version numbers are specified the Compiler replaces any existing type library with the specified new version number If no version numbers are specified and there is an existing type library the Compiler replaces the current version Supported Executable Types When calling mbuild to link a library the d11 file will be component name major minor dll This will prevent new versions from conflicting with each other The user never uses the DLL name It is not necessary to specify this name to the system because COM locates component DLLs using the Window s registry The MATLAB Compiler uses the b option to generate a Visual Basic bas file that contains the Microsoft Excel Formula Function interface to the compiler generated COM object When imported into the workbook this Visual Basic code allows the MATLAB function to be seen as a cell formula function The ioption causes the Compiler to include only the M files that are specif
93. cesses any input arguments and passes them to the implementation version of the function appearing above FF Fe KH X 5 Controlling Code Generation void mlxGasket int nlhs mxArray plhs int nrhs mxArray prhs mxArray mprhs 1 mxArray mplhs 1 int i PP rain gS ae a nies Input Argument Processing xf if nlhs gt 1 mlfError mxCreateString Run time Error File gasket Line 1 Column 1 The function gasket was called with mor e than the declared number of outputs 1 NULL if nrhs gt 1 mlfError mxCreateString Run time Error File gasket Line 1 Column 1 The function gasket was called with mor e than the declared number of inputs 1 NULL for i 0 i lt 1 i mplhs i NULL for i 0 i lt 1 amp amp i lt nrhs i mprhs i prhs i for i lt 1 i mprhs i NULL mlfEnterNewContext O 1 mprhs 0 GL Call to C Implementation Function x mplhs 0 Mgasket nlhs mprhs 0 5 12 Internal Interface Functions 59 Sean e ima Output Argument Processing Ef mlfRestorePreviousContext O 1 mprhs 0 plhs 0 mplhs 0 mlfF Interface Function The Compiler always generates the m1fF interface function which contains the normal C interface to the function This code is the corresponding C interface function m1fGasket from the Sierpinski Gasket example
94. chapter explains how to use the MATLAB Compiler to code and build stand alone applications Stand alone applications run without the help of the MATLAB interpreter In fact stand alone applications run even if MATLAB is not installed on the system However stand alone applications do require the run time shared libraries which are detailed in the corresponding sections Differences Between MEX Files and Stand Alone Applications p 4 2 Building Stand Alone C C Applications p 4 4 Building Stand Alone Applications on UNIX p 4 7 Building Stand Alone Applications on PCs p 4 15 Distributing Stand Alone Applications p 4 27 Building Shared Libraries p 4 30 Building COM Objects p 4 31 Building Excel Plug Ins p 4 32 Troubleshooting p 4 33 Coding with M Files Only p 4 36 Alternative Ways of Compiling M Files p 4 40 Mixing M Files and C or C p 4 42 Overview of the differences Steps to create stand alone C C applications UNIX specific steps to create stand alone applications PC specific steps to create stand alone applications Packaging applications for users Steps to create C shared libraries Steps to create COM objects Steps to create Excel plug ins Common problems with mbuild and the MATLAB Compiler Creating stand alone applications from M files and MEX files Other ways of compiling M files Creating applications from M files and C C code 4 Stand Alone Applications
95. char matrix n 17 mbchar n Error using gt mbchar Argument to mbchar must be of class char mbcharvector mbcharscalar mbreal mbscalar mbvector mbintscalar mbintvector mcc mbcharscalar Purpose Syntax Description Example See Also Assert variable is a character scalar mbcharscalar x The statement mbcharscalar x causes the MATLAB Compiler to impute that x is a character scalar i e an unsigned short variable At run time if mbcharscalar determines that x holds a value other than a character scalar mbcharscalar issues an error message and halts execution of the MEX file mbcharscalar tells the MATLAB interpreter to check whether x holds a character scalar value If x does not mbcharscalar issues an error message and halts execution of the M file The MATLAB interpreter does not use mbcharscalar to impute x Note that mbcharscalar only tests x at the point in an M file or MEX file where an mbcharscalar call appears In other words an mbcharscalar call tests the value of x only once If x becomes a vector after the mbcharscalar test mbcharscalar cannot issue an error message mbcharscalar defines a character scalar as any value that meets the criteria of both mbchar and mbscalar This code in MATLAB generates an error message n hello world mbcharscalar n Error using mbscalar Argument of mbscalar must be scalar mbchar mbcharvector mbreal mbscalar mbv
96. command line are documented in this table Name Description foo m Default version of foo m xxx private foo m foo m private to the xxx directory 5 5 5 Controlling Code Generation 5 6 Name Description cell foo m foo m method to operate on cell arrays cell private foo m foo m private to methods that operate on cell arrays This table lists the functions you can specify on the command line and their corresponding function and filenames Function C Function C Function Filename foo mlfFoo 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 hpp mlfV cell foo xxx private foo mlfXXX private foo XXX private foo XXX private foo c mlxXXX private foo NXXX private foo XXX private foo h mlNXXX private foo VXXX private foo XXX private foo cpp mlfNXXX private foo mlxXXX private foo XXX private foo hpp mlfVXXX private foo Gcell private foo mlfcell private foo cell private foo cell private foo c mlxcell private Foo N cell private foo cell private foo h mlNcell private Foo V cell private foo cell private foo cpp mlfNcell private Foo mlx cell private foo cell private foo hpp mlfVcell private Foo For private functions the name given in the table above may be ambiguous The MATLAB Compiler generates a warning
97. compilations it executes the cshrc script If this script causes unexpected changes to the PATH environment variable an error may occur You can test this by performing a set SHELL bin sh prior to launching MATLAB If this works correctly then you should check your cshrc file for problems setting the PATH environment variable Cannot Locate Your Compiler PC If mouild has difficulty locating your installed compilers it is useful to know how it goes about finding compilers mbuild automatically detects your installed compilers by first searching for locations specified in the following environment variables BORLAND for Borland C C Version 5 3 MSVCDIR for Microsoft Visual C C Version 5 0 6 0 or 7 0 Next mbuild searches the Windows registry for compiler entries Internal Error When Using mbuild setup PC Some antivirus software packages such as Cheyenne AntiVirus and Dr Solomon may conflict with the mbuild setup process If you get an error message during mbuild setup of the following form mex bat internal error in sub get compiler info don t recognize string then you need to disable your antivirus software temporarily and rerun mbuild setup After you have successfully run the setup option you can reenable your antivirus software Verification of mbuild Fails If none of the previous solutions addresses your difficulty with mbuild contact Technical Support at The MathWorks at support mathworks co
98. copts bat 2 16 LD_LIBRARY_PATH run time libraries 4 28 LIBPATH run time libraries 4 28 library path 4 11 shared locating on PC 4 22 locating on UNIX 4 11 shared C 1 16 static C 1 16 wrapper 5 28 libtbx 1 17 license problem 1 8 2 17 2 27 4 35 license dat file 2 6 2 17 licensing 1 7 limitations PC compilers 2 15 UNIX compilers 2 5 Index limitations of MATLAB Compiler 2 0 1 18 built in functions 1 18 exist 1 18 objects 1 18 script M file 1 18 line directives 5 42 line numbers 7 38 Linux 2 4 locating shared libraries on UNIX 4 11 M M option flag 7 47 m option flag 4 37 7 32 macro option 3 6 B pcode 7 35 B sgl 7 35 B sglcpp 7 35 m 7 32 p 7 32 S 7 33 x 7 33 main program 5 22 main wrapper 5 22 main m 4 36 makefile 4 10 mangled function names 5 29 MATLAB add in for Visual Studio 2 22 4 23 configuring on Windows 98 4 25 configuring on Windows ME 4 25 MATLAB Compiler annotating code 5 40 capabilities 1 2 1 14 code produced 1 9 compiling MATLAB provided M files 4 40 creating MEX files 1 9 error messages B 1 executable types 1 9 flags 3 6 formatting code 5 35 generated files 5 3 generated header files 5 8 generated interface functions 5 11 generated wrapper functions 5 21 generating MEX Files 2 2 generating source files 5 21 getting started 3 1 installing on PC 2 18 UNIX 2 4 2 6 installing on Microsoft Windows 2 17 license 1 7 limitations 1 18 macro 7 26 new features 1 4 1 5 opti
99. cro Options mcc m W none test m is equivalent to mcc t W main L C T link exe h W none test m In this example there are two conflicting W options After working from left to right the Compiler determines that the rightmost option takes precedence namely W none and the Compiler does not generate a wrapper Note Macros and regular options may both affect the same settings and may therefore override each other depending on their order in the command line Handling Full Pathnames If you specify a full pathname to an M file on the mcc command line the Compiler 1 Breaks the full name into the corresponding path and filenames lt path gt and lt file gt 2 Replaces the full pathname in the argument list with I path lt file gt For example mcc m home user myfile m would be treated as mcc m I home user myfile m In rare situations this behavior can lead to a potential source of confusion For example suppose you have two different M files that are both named myfile m and they reside in home user dir1 and home user dir2 The command mcc m I home user dir1 home user dir2 myfile m would be equivalent to 7 29 mcc 7 30 mcc m I home user dir1 I home user dir2 myfile m The Compiler finds the myfile min diri 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 op
100. crosoft Windows 2 22 UNIX 2 10 for code hiding 1 16 generating with MATLAB Compiler 2 2 invoking 3 4 precedence 3 4 problems 2 25 2 26 segmentation error 2 25 timing 3 4 troubleshooting 2 25 MEX function 7 33 mexopts bat 2 16 MFC42 d11 4 28 Index M file compiling embedded 7 30 example gasket m 3 2 houdini m 3 10 main m 4 36 mrank m 4 36 4 42 function 3 10 MATLAB provided 4 40 script 1 18 3 10 M files searching for callback strings 1 21 mglinstaller 4 27 mglinstaller exe 4 28 Microsoft Interface Definition Language MIDL compiler 4 31 4 32 Microsoft Visual C 2 14 environment variable 2 26 Microsoft Windows building stand alone applications 4 15 Compiler installation 2 13 system requirements 2 13 Microsoft Windows registry 2 26 MIDL compiler 4 31 4 32 mlib files 5 24 5 26 mrank m 4 36 4 42 MSVC See Microsoft Visual C msvc50opts bat 2 16 msvc60opts bat 2 16 msvc70opts bat 2 16 mwMatrix data type 1 17 N nargout interface function 5 13 5 18 new features 1 4 1 5 normal interface function 5 13 5 17 O o option flag 7 44 objects Handle Graphics axes 1 21 controls 1 21 figures 1 21 menus 1 21 optimize_conditionals optimization 6 9 optimize_integer_for_loops optimization 6 6 optimizing performance 6 1 conditionals 6 9 disabling all 6 2 enabling all 6 2 enabling selected 6 2 listing all optimizations 6 3 loop simplification 6 6 nonscalar arrays 6 4 0 optimization option 6 2 0 all
101. ctives To include line directives in your generated C or C code use mcc A line on The Hello World example produces the following code segment when this option is selected Note that several lines have been truncated for readability Zline 1 D work hello m Line 1 static void Mhello void line 1 D work hello m Line 1 mclMlineEnterFunction D work hello m hello line 1 D work hello m Line 1 7 mexLocalFunctionTable save local function table gt line 1 D work hello m Line 1 mxArray ans NULL s This is the hello world function written in M code fprintf 1 Hello World in kf line 3 D work hello m Line 3 mclMline 3 line 3 D work hello m Line 3 mclAssignAns amp ans mlfNFprintf O mlfScalar 1 mxCreateString Hello gt line 3 D work hello m Line 3 mxDestroyArray ans line 3 D work hello m Line 3 mclSetCurrentLocalFunctionTable save local function table line 3 D work hello m Line 3 mclMlineExitFunction line 3 D work hello m Line 3 In this example Line 1 points to lines in the generated C code that were produced by line 1 from the M file that is function hello Line 3 points to lines in the C code that were produced by line 3 of the M file or fprintf 1 Hello World n 5 43 5 Controlling Code Generation Controlling Information in Run Time E
102. d not be bound to a function that is known at compile time A run time error will occur if this code is executed no_matching_function The called function was not found on the search path Warning File filename Line Column Attempt to clear value when it has not been previously defined clear_undefined_value The variable was cleared with the clear command prior to being defined Warning File filename Line Column Future versions of MATLAB will require that whitespace a comma or a semicolon separate elements of a matrix Please type help matrix_element_separators at the MATLAB prompt for more information separator_needed It is still possible to leave out all separators when constructing a matrix For example 5 5 5 has no separators It is equivalent to 5 5 0 5 Warning File filename Line Column References to functionname require the C C Graphics Library when executing in stand alone mode You must specify B sgl or B sglcpp in order to use the C C Graphics Library A run time error will occur if the C C Graphics Library is not present using graphics function This warning is produced when a Graphics Library call is present in the code It is only generated when producing the main or library wrapper and not during normal compilation unless it is specifically enabled Warning File filename Line Column References to variablename will produce a run time error because it is an undefined functi
103. d script they use it in its simplest form For complete information about the mbuild script and its options see the mbuild reference page Using an Integrated Development Environment The MathWorks provides a MATLAB add in for the Visual Studio development system that lets you work easily within the Microsoft Visual C C MSVC integrated development environment IDE The MATLAB add in for Visual Studio greatly simplifies using M files in the MSVC environment The add in automates the integration of M files into Visual C projects It is fully integrated with the MSVC environment 4 23 4 Stand Alone Applications 4 24 Note The MATLAB add in for Visual Studio does not currently work with Microsoft Visual C C Version 7 0 The add in for Visual Studio is automatically installed on your system when yourun either mbuild setup or mex setup and select Microsoft Visual C C version 5 or 6 However there are several steps you must follow in order to use the add in 1 To build MEX files with the add in for Visual Studio run the following command at the MATLAB command prompt mex setup Follow the menus and choose either Microsoft Visual C C 5 0 or 6 0 This configures mex to use the selected Microsoft compiler and also installs the necessary add in files in your Microsoft Visual C C directories 2 To build stand alone applications with the MATLAB add in for Visual Studio requires the MATLAB Compiler and the MATLAB
104. de Using this Guide This book describes the MATLAB Compiler and provides numerous examples of how to use it The topics included are ntroducing the MATLAB Compiler describes the new features of the Compiler and provides an overview of how to use it nstallation and Configuration discusses how to install and configure the Compiler and how to verify that your system is properly set up Working with MEX Files describes how to compile M files with the MATLAB Compiler e Stand Alone Applications explains how to use the MATLAB Compiler to code and build stand alone applications Controlling Code Generation describes the code generated by the MATLAB Compiler and the options that you can use to control code generation Optimizing Performance describes optimizations you can perform on your M file source code that can improve the performance of the generated C C code Reference provides the set of reference pages that describe the Compiler pragmas functions and command line tools MATLAB Compiler Quick Reference is a quick reference of all the Compiler functions Error and Warning Messages lists and describes error messages and warnings generated by the MATLAB Compiler xi Preface xii Typographical Conventions This manual uses some or all of these conventions Item Convention Example Example code Function names syntax filenames directory f
105. debugging You should specify Gif you want to debug the MEX file or stand alone application with a debugger M string Direct Pass Through Pass string directly to the mex or mbuild script This provides a useful mechanism for defining compile time options e g M Dmacro value 7 47 mcc Examples 7 48 Note Multiple M options do not accumulate only the last M option is used z lt path gt Specifying Library Paths Specify the path to use for library and include files This option uses the specified path for compiler libraries instead of the path returned by matlabroot Make a C translation and a MEX file for myfun m mcc x myfun Make a C translation and a stand alone executable for myfun m mcc m myfun Make a C translation and a stand alone executable for myfun m mcc p myfun 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 min the files source directory and put the resulting C files and executable in the files target directory mcc m I files source d files target myfun Make a C translation and a MEX file for myfun m Also translate and include all M functions called directly or indirectly by myf
106. ding with M Files Only 0 0 000 aee 4 36 Alternative Ways of Compiling M Files 4 40 Compiling MATLAB Provided M Files Separately 4 40 Compiling mrank m and rank m as Helper Functions 4 41 Mixing M Files and C or C 0 00 0 ee eee eee 4 42 Simple Example 0 a cece eee eens 4 42 Advanced C Example 0 0 cece ene nnes 4 47 Controlling Code Generation 5 Code Generation Overview eens 5 2 Example M Files 4 esee Ree Rh ra 5 2 Generated Codes oed os cecus eR Peur us 5 3 Compiling Private and Method Functions 5 5 The Generated Header Files LLL 5 8 C Header File 5 ex d awe we Ade die d 5 8 C H ader File nar Loses EC tee SES a 5 9 Internal Interface Functions s ss 5 11 C Interface Functions 0 0 0 5 11 C Interface Functions 0 0 ccc eens 5 16 Supported Executable Types 0 0005 5 21 Generating Files 0 0 0 eens 5 21 MEX Files ud ine Sk a eh ae bea Ou a aka Mae n 5 22 Main Filesz osse tua LE lx SC e 5 22 Simulink S Functions 0 0 ccc cee eee 5 24 C lIabraries 5 uro ee Be anaes ee ea eas 5 24 C Shared Library css pe sae shane ba Y MEER 5 25 C Libraries 2 i055 ed Beis a eee ies 5 28 COM Components 0 ccc eee eee ene eens 5 29 Porting Generated Code to a Different Platform 5 34
107. doesn t exist in your MATLAB directory the system displays a message stating that the options file is being copied to your user specific matlab directory If an options file already exists in your MATLAB directory the system prompts you to overwrite it UNIX Workstation Note The setup option creates a user specific matlab directory in your individual home directory and copies the appropriate options file to the directory If the directory already exists a new one is not created This matlab directory is used for your individual options files only each user can have his or her own default options files other MATLAB products may place options files in this directory Do not confuse these user specific matlab directories with the system matlab directory where MATLAB is installed Using the setup option resets your default compiler so that the new compiler is used every time you use the mex script Modifying the Options File Another use of the setup option is if you want to change your options file settings For example if you want to make a change to the current linker settings or you want to disable a particular set of warnings you should use the setup option As the previous note says setup copies the appropriate options file to your individual directory To make your user specific changes to the options file you then edit your copy of the options file to correspond to your specific needs and save the modified file Thi
108. dures in that library Error optionname is not a valid option option argument You must use an argument that corresponds to the option For example mcc L Cpp Correct mcc L COBOL Incorrect Error Out of memory Typically this message occurs because the Compiler requests a larger segment of memory from the operating system than is currently available Adding additional memory to your system could alleviate this problem Error Previous warning treated as error When you use the w error option this error displays immediately after a warning message B 7 B Eror and Warning Messages B 8 Error The argument after the option option must contain a colon The format for this argument requires a colon For more information see MATLAB Compiler Option Flags on page 7 31 or type mcc at the command prompt Error The environment variable MATLAB must be set to the MATLAB root directory On UNIX the MATLAB and LM LICENSE FILE variables must be set The mcc shell script does this automatically when it is called the first time Error The file filename cannot be written When generating an mlib file the Compiler cannot write out the mlib file Error The license manager failed to initialize error code is errornumber You do not have a valid Compiler license or no additional Compiler licenses are available Error The option option is invalid in modename mode specify for help The specified option is not avai
109. e Column variablename has been declared both as GLOBAL and PERSISTENT Declare variables as either global or persistent Compile Time Errors Error Found illegal whitespace character in command line option string The strings on the left and right side of the space should be separate arguments to MCC For example mcc A none Correct mcc A none Incorrect Error Improper usage of option optionname Type mcc for usage information You have incorrectly used a Compiler option For more information about Compiler options see MATLAB Compiler Option Flags on page 7 31 or type mcc at the command prompt Error languagename is not a known language The dialect option was given a language argument for which there is no support yet For example mcc m D japanese sample m Correct mcc m D german sample m Incorrect Error libraryname library not found MATLAB has been installed incorrectly Error MEX File mexfilename cannot be compiled into P Code Only M files can be compiled into P code MEX files cannot be compiled into P code Error No source files were specified for help You must provide the Compiler with the name of the source file s to compile Error On UNIX the name of an MLIB file must begin with the letters lib filename does not adhere to this rule The mlib file specified on the command line does not start with the letters lib and the file being compiled uses proce
110. e using mex only function This warning is produced if you call any built in function that is only available in mex mode It is only generated when producing the mainor lib wrapper and not during normal compilation unless specifically enabled B Eror and Warning Messages Warning File filename Line Column The load statement cannot be translated unless it specifically lists the names of variables to be loaded as constant strings load_without_constant_strings Use one of the forms of the load command that contains the names of the variables to be loaded for example load filename numor y load filename Warning File filename Line Column The logical expression s involving OR and AND operators may have returned a different result in previous versions of MATLAB due to a change in logical operator precedence Use parentheses to make your code insensitive to this change Please type help precedence for more information and_or_precedence Starting in MATLAB 6 0 the precedence of the logical AND amp and logical OR operators now obeys the standard relationship AND being higher precedence than OR and the formal rules of Boolean algebra as implemented in most other programming languages as well as Simulink and Stateflow Previously MATLAB would incorrectly treat the expression y a amp b c amp d as y a amp b c amp d It now correctly treats it as y a amp b c amp d The form y a
111. e Even if you are not producing a separate library you must generate a library wrapper file when including any Compiler generated code into a larger application 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 Refer to your vendor supplied documentation for details on creating C shared libraries libtimefun cpp The C wrapper file libtimefun cpp initializes the state of Compiler generated functions so that those functions can be called from C code not generated by the Compiler These files are produced from the command mcc W lib libtimefun L Cpp weekday date tic calendar toc or using the cpplib bundle file mcc B cpplib libtimefun weekday date tic calendar toc COM Components The COM wrapper file allows you to create COM components from MATLAB M files The Compiler options that generate the COM wrappers are W com lt component_name gt lt class_name gt lt major gt lt minor gt W comhg lt component_name gt lt class_name gt lt maj
112. e a list of all the current compiler settings To change the options use an editor to make changes to your options file which is in your local matlab directory Your local matlab directory is a user specific MATLAB directory in your individual home directory that is used specifically for your individual options files You can also embed the settings obtained from the verbose option of mbuild into an integrated development environment IDE or makefile that you need to maintain outside of MATLAB Often however it is easier to call mbuild from your makefile See your system documentation for information on writing makefiles Note Any changes made to the local options file will be overwritten if you execute mbuild setup To make the changes persist through repeated uses of mbuild setup you must edit the master file itself matlab bin mbuildopts sh Temporarily Changing the Compiler To temporarily change your C or C compiler use the f option as in mbuild f file The f option tells the mbuild script to use the options file file If lt file gt is not in the current directory then file must be the full pathname to the desired options file Using the f option tells the mbuild script to use the specified options file for the current execution of mbuild only it does not reset the default compiler Building Stand Alone Applications on UNIX Verifying mbuild There is C source code for an example ex1 c includ
113. e more than the default amount of environment space If you get the error out of environment space add this line to your config sys file shell c command com e 32768 p On Windows Me systems if you encounter this problem and are using the MATLAB add in for Visual Studio follow the procedure in Configuring on Windows 98 and Windows Me Systems on page 4 25 Directory or File Not Writeable If a destination directory or file is not writeable ensure that the permissions are properly set In certain cases make sure that the file is not in use mbuild Generates Errors On UNIX if you run mbuild filename and get errors it may be because you are not using the proper options file Run mbuild setup to ensure proper compiler and linker settings Compiler and or Linker Not Found On PCs running Windows if you get errors such as unrecognized command or file not found make sure the command line tools are installed and the path and other environment variables are set correctly in the options file mbuild Not a Recognized Command If mbuild is not recognized verify that MATLAB V bin is on your path On UNIX it may be necessary to rehash 4 33 4 Stand Alone Applications 4 34 mbuild Works from Shell but Not from MATLAB UNIX If the command mbuild ex1 c works from the UNIX command prompt but does not work from the MATLAB prompt you may have a problem with your cshrc file When MATLAB launches a new C shell to perform
114. e this with the O none option you get mclForLoopIterator viter for mclForStart amp viter mlfScalar 1 mclMinus mlfLength mclVa x x mlfScalar 1 NULL mclForNext amp viter amp i 1 mclDestroyForLoopIterator viter Compiling with 0 none O optimize integer for loops on gives int v mclForIntStart 1 int e mclLengthInt mclVa x x 1 if v_ gt e_ f mlfAssign amp i mxarrayO else 6 7 6 Optimizing Performance for 1 if v e break tV 3 mlfAssign amp i mlfScalar v Optimizing Conditionals Optimizing Conditionals optimize conditionals This optimization reduces the MATLAB conditional operators to scalar C conditional operators when both operands are known to be integer scalars The Compiler knows that nargin nargout and for loop control variables when using the above optimization are integer scalars For example function test a b c d if nargin 4 d 0 0 end If you compile this with the O none option you get if mlfTobool mclLt mlfScalar nargin mlfScalar 4 1 Compiling with 0 none O optimize conditionals on gives if nargin_ 4 6 9 6 Optimizing Performance Optimizing MATLAB Arrays Scalars percolate simple types This optimization reduces the strength of operations on simple types scalars by reducing operations to scalar double operations whenever possible For example if your code use
115. ector mbintscalar mbintvector mcc 7 9 mbcharvector Purpose Syntax Description Example See Also 7 10 Assert variable is a character vector i e a MATLAB string mbcharvector x The statement mbcharvector x causes the MATLAB Compiler to impute that x is a char vector At run time if mocharvector determines that x holds a value other than a char vector mbcharvector issues an error message and halts execution of the MEX file mbcharvector tells the MATLAB interpreter to check whether x holds a char vector value If x does not mocharvector issues an error message and halts execution of the M file The MATLAB interpreter does not use mbcharvector to impute x Note that mbcharvector only tests x at the point in an M file or MEX file where an mbcharvector call appears In other words an mbcharvector call tests the value of x only once If x becomes something other than a char vector after the mbcharvector test mocharvector cannot issue an error message mbcharvector defines a char vector as any value that meets the criteria of both mbchar and mbvector Note that mbcharvector considers char scalars as char vectors as well This code in MATLAB causes mbcharvector to generate an error message because although n is a vector n contains one value that is not a char n 1 5 mbcharvector n Error using gt mbchar Argument to mbchar must be of class char mbchar mbcharscalar mbreal mbscala
116. ector value If x does not mbrealvector issues an error message and halts execution of the M file The MATLAB interpreter does not use mbrealvector to impute x Note that mbrealvector only tests x at the point in an M file or MEX file where an mbrealvector call appears In other words an mbrealvector call tests the value of x only once If x becomes complex after the mbrealvector test mbrealvector cannot issue an error message mbrealvector defines a real vector as any value that meets the criteria of both mbreal and mbvector Note that mbrealvector considers real scalars to be real vectors as well This code in MATLAB causes mbrealvector to generate an error message because although n is a vector n contains one imaginary number n 5 2 3i mbrealvector n Error using mbreal Argument to mbreal must be real mbreal mbrealscalar mbvector mcc 7 17 mbscalar Purpose Syntax Description Example See Also 7 18 Assert variable is scalar mbscalar n The statement mbscalar x causes the MATLAB Compiler to impute that x is a scalar At run time if mbscalar determines that x holds a nonscalar value mbscalar issues an error message and halts execution of the MEX file mbscalar tells the MATLAB interpreter to check whether x holds a scalar value If x does not mbscalar issues an error message and halts execution of the M file The MATLAB interpreter does not use mbscalar to impute x Note that
117. ecutable files in the directory dirname Do not combine this option with output if the output option gives a full pathname Create an executable named lt resultname gt An appropriate executable extension is automatically appended Overrides the mbuild default executable naming mechanism 7 22 mbuild Table 7 1 mbuild Options Continued Option Description regsvr setup U lt name gt Windows Use the regsvr32 program to register the resulting shared library at the end of compilation The Compiler uses this option whenever it produces a COM wrapper file Interactively specify the compiler options file to use as default for future invocations of mbuild by placing it in lt UserProfile gt Application Data MathWorks MATLAB R13 Windows or HOME matlab R13 UNIX When this option is specified no other command line input is accepted Remove any initial definition of the C preprocessor symbol lt name gt Inverse of the D option Verbose Print the values for important internal variables after the options file is processed and all command line arguments are considered Prints each compile step and final link step fully evaluated to see which options and files were used Very useful for debugging 7 23 mbuild Table 7 1 mbuild Options Continued Option Description lt name gt lt value gt lt name gt lt value gt UNIX Override an options file varia
118. ed in the lt matlab gt extern examples cmath directory where lt matlab gt represents the top level directory where MATLAB is installed on your system To verify that mbuild is properly configured on your system to create stand alone applications copy ex1 c to your local directory and type cd to change to that directory Then at the MATLAB prompt enter mbuild ex c This creates the file called ex1 Stand alone applications created on UNIX systems do not have any extensions Locating Shared Libraries Before you can run your stand alone application you must tell the system where the API and C shared libraries reside This table provides the necessary UNIX commands depending on your system s architecture Architecture Command HP700 HP UX setenv SHLIB PATH matlab extern lib arch SHLIB PATH IBM RS 6000 setenv LIBPATH matlab extern lib ibm rs LIBPATH All others setenv LD_LIBRARY_PATH matlab extern lib arch LD LIBRARY PATH where matlab is the MATLAB root directory arch is your architecture i e alpha hp700 hpux 1nx86 sgi sgi64 or so12 It is convenient to place this command in a startup script such as cshrc Then the system will be able to locate these shared libraries automatically and you will not have to reissue the command at the start of each login session Note On all UNIX platforms the Compiler library is shipped as a shared object so file or shared library s1
119. efault Compiler To change your default C or C compiler you select a different options file You can do this at any time by using the mex setup option This example shows the process of changing your default compiler to the Microsoft Visual C C Version 6 0 compiler mex setup Please choose your compiler for building external interface MEX files Would you like mex to locate installed compilers y n n Select a compiler 1 Borland C Builder version 2 Borland C Builder version 3 Borland C Builder version 4 Borland C Builder version 5 Borland C C version 5 02 6 Borland C C version 5 0 7 Borland C C free command line tools version 5 5 8 Compaq Visual Fortran version 6 6 9 Compaq Visual Fortran version 6 1 10 Digital Visual Fortran version 6 5 ORO OD ooo o 0 11 Digital Visual Fortran version 5 0 12 Lcc C version 2 4 13 Microsoft Visual C C version 7 0 14 Microsoft Visual C C version 6 0 Microsoft Windows on PCs 15 Microsoft Visual C C version 5 0 16 WATCOM C C version 11 17 WATCOM C C version 10 6 0 None Compiler 14 Your machine has a Microsoft Visual C C compiler located at D Applications Microsoft Visual Studio Do you want to use this compiler y n y Please verify your choices Compiler Microsoft Visual C C 6 0 Location D Applications Microsoft Visual Studio Are these correct y n y The default options file C WINN
120. elhg component name class name version T link lib h libmmfile mlib b i B csglsharedlib C Handle Graphics Shared Library Produce a C shared library that uses Handle Graphics The B csglsharedlib option is equivalent to the series of options t W libhg shared library name T link lib h libmmfile mlib libmwsglm mlib B cppcom C COM Object Produce a C COM object The B cppcom option is equivalent to the series of options B ccom component name class name version L cpp B cppexcel C Excel COM Object Produce a C Excel COM object The B cppexcel option is equivalent to the series of options B cexcel component name class name version L cpp B cppsglcom C Handle Graphics COM Object Produce a C COM object that uses Handle Graphics The B cppsglcom option is equivalent to the series of options B csglcom lt component_name gt lt class_name gt lt version gt L cpp B cppsglexcel C Handle Graphics Excel COM Object Produce a C Excel COM object that uses Handle Graphics The B cppsglexcel option is equivalent to the series of options B csglexcel lt component_name gt lt class_name gt lt version gt L cpp B cpplib C Library Produce a C library The B cpplib option is equivalent to the series of options B csharedlib shared library name L cpp T compile lib mcc B csharedlib C Shared Library Produce a C shared library The B csharedli
121. ent Installation options Installing debugger files Microsoft Foundation Classes MFC 16 bit DLL executables ActiveX Running from the command line Updating the registry Installing Microsoft Visual C C Version 6 0 We recommend that you do a full installation of your compiler If you do a partial installation you may omit a component that the MATLAB Compiler relies on For the purposes of the MATLAB Compiler it is not necessary to install debugger DBG files However you may need them for other purposes This is not required This is not required This is not required Make sure you select all relevant options for running your compiler from the command line If your installer gives you the option of updating the registry you should do it If you need to change the location where this compiler is installed you must change the location of the Common directory Do not change the location of the VC98 directory from its default setting Microsoft Windows on PCs mex Verification Choosing a Compiler Systems with Exactly One C C Compiler If you have properly installed the MATLAB Compiler and your supported C or C compiler you can now create C MEX files On systems where there is exactly one C or C compiler available to you the mex utility automatically configures itself for the appropriate compiler So for many users to create a C MEX file you can simply enter mex filename c
122. ents of a 3 by 3 matrix a and then displays the contents of scalar b 6 2832 84 5575i 25 1327 25 1327i 43 9823 43 9823i 12 5664 34 5575i1 31 4159 31 41591 50 2655 28 2743i 18 8496 18 8496i1 37 6991 37 69911 56 5487 28 2743i 143 4164 An Explanation of This C Code Invoking the MATLAB Compiler on multarg m generates the C function prototype extern mxArray mlfMultarg mxArray b mxArray x mxArray y extern void mlxMultarg int nlhs mxArray plhs int nrhs mxArray prhs This C function header shows two input arguments mxArray x and mxArray y and two output arguments the return value and mxArray b Use mxCreateDoubleMatrix to create the two input matrices x and y Both x and y contain real and imaginary components The memcpy function initializes the components for example x mxCreateDoubleMatrix ROWS COLS COMPLEX memcpy mxGetPr x x pr ROWS COLS sizeof double memcpy mxGetPi y y pi ROWS COLS sizeof double The code in this example initializes variable x from two arrays x pr and x pi of predefined constants more realistic example would read the array values from a data file or a database After creating the input matrices main calls mlfMultarg a mxArray mlfMultarg amp b x y 4 49 4 Stand Alone Applications The mlfMultarg function returns matrices a and b a has both real and imaginary components b is a scalar having only a real component T
123. equal Compile Time Errors Error File filename Line Column indexing must appear last in an index expression If you use ordinary array indexing to index into an expression it must be last in the index expression For example you can use X 1 value and X12 1 but you cannot use X value 1 or X 1 2 Error File filename Line Column A CONTINUE may only be used within a FOR or WHILE loop Use Continue to pass control to the next iteration of a for or while loop Error File filename Line Column A function declaration cannot appear within a script Mile There is a function declaration in the file to be compiled but it is not at the beginning of the file Scripts cannot have any function declarations function M files must start with a function Error File filename Line Column Assignment statements cannot produce a result An assignment statement cannot be used in a place where an expression but not a statement is expected In particular this message often identifies errors where an assignment was used but an equality test was intended For example if x y z w end Correct if x y Zz w end Incorrect Error File filename Line Column A variable cannot be made storageclass1 after being used as a storageclass2 You cannot change a variable s storage class global local persistent Even though MATLAB allows this type of change in scope the Compiler does not Error File f
124. er and the MATLAB C Math Library If mbuild cannot deduce from the file extensions whether to compile C or C mbuild invokes the C compiler The MATLAB Compiler generates only c and cpp files Table 4 1 UNIX File Extensions for mbuild shows the supported file extensions Table 4 1 UNIX File Extensions for mbuild Language Extension s C C C Cpp C CXX CC Note You can override the language choice that is determined from the extension by using the lang option of mbuild For more information about this option as well as all of the other mbuild options see the mbuild reference page 4 Stand Alone Applications 4 8 Locating Options Files mbuild locates your options file by searching the following The current directory e HOME matlab R13 e lt matlab gt bin mbuild uses the first occurrence of the options file it finds If no options file is found mbuild displays an error message Preparing to Compile Note Refer to Supported ANSI C and C UNIX Compilers on page 2 4 for information about supported compilers and important limitations Using the System Compiler If the MATLAB Compiler and your supported C or C compiler are installed on your system you are ready to create C or C stand alone applications To create a stand alone C application you can simply enter mbuild filename c This simple method works for the majority of users Assuming filename c contains a main
125. er Options Files on the PC Compiler Master Options File Borland C Builder Version 3 0 bcc53compp bat Borland C Builder Version 4 0 bcc54compp bat Borland C Builder Version 5 0 bcc55compp bat Borland C Builder Version 6 0 bcc56compp bat Lec C Version 2 4 lccopts bat Microsoft Visual C C Version 5 0 msvc50compp bat Building Stand Alone Applications on PCs Table 4 3 Compiler Options Files on the PC Continued Compiler Master Options File Microsoft Visual C C Version 6 0 msvc60compp bat Microsoft Visual C C Version 7 0 msvc70compp bat Combining Customized C and C Options Files The options files for mbuild have changed as of MATLAB 5 3 Release 11 so that the same options file can be used to create both C and C stand alone applications If you have modified your own separate options files to create C and C applications you can combine them into one options file To combine your existing options files into one universal C and C options file 1 Copy from the C options file to the C options file all lines that set the variables COMPFLAGS OPTIMFLAGS DEBUGFLAGS and LINKFLAGS 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 Te
126. es Before You Begin Before reading this book you should already be comfortable writing M files If you are not see Programming and Data Types in the MATLAB documentation Introduction Note The phrase MATLAB interpreter refers to the application that accepts MATLAB commands executes M files and MEX files and behaves as described in the Using MATLAB documentation When you use MATLAB you are using the MATLAB interpreter The phrase MATLAB Compiler refers to this product which translates M files to C or C source code and its associated libraries This book distinguishes references to the MATLAB Compiler by using the word Compiler with a capital C References to compiler with a lowercase c refer to your C or C compiler Introducing the MATLAB Compiler New Features MATLAB Compiler 3 0 The MATLAB Compiler now includes the MATLAB C C Math and Graphics Libraries Note Asthe MATLAB Compiler evolves it will support additional standard platform interfaces such as COM Java and CORBA Consequently the requirement of developing code specifically for the MATLAB C C Math Library will diminish Once this happens the Math Library will no longer support code written directly for the Library The Compiler will continue to use the MATLAB C C Math Library as it currently does Anew optimization is available that allows the Compiler to use simpler types for variables at run time when possible
127. escription and the warning message identifier string in parentheses that you can enable or disable with the w option For example to enable the display of warnings related to undefined variables you can use mcc w enable undefined variable To enable all warnings except those generated by the save command use mcc w enable w disable save options To display a list of all the warning message identifier strings use mcc w list For additional information about the w option see MATLAB Compiler Option Flags on page 7 31 Warning PM Warning message path manager warning The path manager can experience file I O problems when reading the directory structure permissions Warning PMI message path manager inform This is an informational path manager message Warning A line has number characters violating the maximum page width width max page width violation To increase the maximum page width use the F page width n option and set n to a larger value Warning File filename Line Column A BREAK statement appeared outside of a loop This BREAK is interpreted as a RETURN break without loop The break statement should be used in conjunction with the for or while statements When not used in conjunction with these statements the break statement acts as a return from a function B Eror and Warning Messages Warning File filename Line Column The call to function functionname on this line coul
128. files is translated into a single COM class MATLAB COM Builder supports multiple classes per component The interface to the COM class is the same set of functions that are exported from a C shared library but the Compiler supports both C and C code generation in producing COM objects mbuild automatically Invokes the Microsoft Interface Definition Language MIDL compiler Invokes the resource compiler Specifies the DEF files Using mbuild options you can enable auto registration of the COM compatible DLL Note Creating COM objects from MATLAB M files is available on Windows only The only compilers that support the building of COM objects with the MATLAB Compiler are Borland C Builder versions 3 0 4 0 and 5 0 and Microsoft Visual C C versions 5 0 6 0 and 7 0 For example to compile plus1 minto a COM object use mcc B ccom addin addin 1 0 plus1 m For more information see the MATLAB COM Builder documentation 4 31 4 Stand Alone Applications Building Excel Plug Ins 4 32 Note To create Excel plug ins from the MATLAB Compiler you must have the MATLAB Excel Builder installed on your system You can use mbuild to create a COM object from MATLAB M files that can be used as an Excel plug in The collection of M files is translated into a single Excel plug in MATLAB Excel Builder supports one class per component The interface to the COM class is the same set of functions that are expo
129. fined in a P file is detected B Eror and Warning Messages Warning M file filename was specified on the command line with full path of pathname but was found on the search path in directory directoryname first specified_file_mismatch The Compiler detected an inconsistency between the location of the M file as given on the command line and in the search path The Compiler uses the location in the search path This warning occurs when you specify a full pathname on the mcc command line and a file with the same base name filename is found earlier on the search path This warning is issued in the following example if the file afile m exists in both dir1 and dir2 mcc x I dir1 dir2 afile m Warning No M function source available for functionname assuming function varargout functionnamelvarargin NOTE This will produce a link error in stand alone code unless you provide a handwritten definition for this function using stub function The Compiler found a p or mex version of the function and is substituting a generic function declaration in its place Warning Overriding the F page width setting to width due to presence of A line on setting page width override The A line on setting overrides the page width This warning reminds you that the F setting although present has no effect Warning The function functionname is an intrinsic MATLAB function The signature of the function found in file filename doe
130. g 7 41 B pcode option flag 7 35 B sgl option flag 7 35 B sglcpp option flag 7 35 bcc53opts bat 2 16 bcc54opts bat 2 16 bcc550pts bat 2 16 bcc56opts bat 2 16 Borland compiler 2 14 environment variable 2 26 bundle file option 5 25 7 41 bundle files 7 42 bundling compiler options B option flag 7 41 C c option flag 7 43 C compilers supported on PCs 2 14 supported on UNIX 2 4 generating 7 43 interfacing to M code 5 46 shared library wrapper 5 24 I 1 Index 1 2 C compilers supported on PCs 2 14 supported on UNIX 2 4 interfacing to M code 5 46 library wrapper 5 28 required features templates 4 6 callback problems fixing 1 20 callback strings searching M files for 1 21 changing compiler on PC 2 20 changing license file Y option flag 7 47 code controlling 21ine directives 5 42 controlling comments in 5 40 controlling run time error information 5 44 hiding 1 16 porting 5 34 setting indentation 5 35 setting width 5 35 COM component wrapper 5 29 COM object building 4 31 files created 5 30 interface 4 31 4 32 support 4 31 supported compilers 4 31 4 32 command duality 5 22 compiler C requirements 4 6 changing default on PC 4 18 changing default on UNIX 4 8 changing on PC 2 20 choosing on PC 4 17 choosing on UNIX 4 8 MIDL 4 31 4 32 resource 4 31 4 32 selecting on PC 2 19 Compiler 2 1 See MATLAB Compiler Compiler 2 3 See MATLAB Compiler Compiler library on UNIX 4 11 Compiler See MATL
131. g of COM objects are Borland C Builder versions 3 0 4 0 5 0 and 6 0 and Microsoft Visual C C versions 5 0 6 0 and 7 0 Building Stand Alone Applications on PCs Choosing a Compiler Systems with Exactly One C C Compiler If the MATLAB Compiler and your supported C or C compiler are installed on your system you are ready to create C or C stand alone applications On systems where there is exactly one C or C compiler available to you the mbuild utility automatically configures itself for the appropriate compiler So for many users to create a C or C stand alone applications you can simply enter mbuild filename c This simple method works for the majority of users Assuming filename c contains a main function this example uses your installed C or C compiler as your default compiler for creating your stand alone application If you are a user who does not need to change compilers or you do not need to modify your compiler options files you can skip ahead in this section to Verifying mbuild on page 4 22 If you need to know how to change the options file or select a different compiler continue with this section Note On Windows 98 systems if you get the error out of environment space see Out of Environment Space Running mex or mbuild on page 4 33 for more information Systems with More than One C C Compiler On systems where there is more than one C or C compiler the mbuild utility lets
132. ge width 5 35 Fortran 2 26 full pathnames handling 7 29 s function 5 48 7 6 function calling from M code 5 46 comparison to scripts 3 10 compiling method 5 5 private 5 5 duality 5 22 feval interface 5 11 5 16 hand written implementation version 5 46 helper 4 41 implementation version 5 11 interface 5 11 mangled name 5 29 nargout interface 5 13 5 18 normal interface 5 13 5 17 unsupported in stand alone mode 1 19 void interface 5 15 5 20 wrapper 5 21 W option flag 7 39 function M file 3 10 I 3 Index I 4 G G option flag 7 47 g option flag 7 31 gasket m 3 2 gcc compiler 2 4 generated Compiler files 5 3 generating P code 7 35 graphics applications trouble starting 4 28 H h option flag 7 43 Handle Graphics Callback property 1 21 objects 1 21 header file C example 5 8 C example 5 9 helper functions h option 7 43 in stand alone applications 4 41 hiding code 1 16 l i option 7 44 I option flag 7 44 IDE using an 4 23 indentation setting 5 37 inputs dynamically sized 3 7 setting number 3 8 installation Microsoft Windows 2 13 PC 2 14 verify from DOS prompt 2 23 verify from MATLAB prompt 2 23 UNIX 2 4 verify from MATLAB prompt 2 11 verify from UNIX prompt 2 11 integrated development environment using 4 23 interface function 5 11 interfacing M code to C C code 5 46 internal error B 1 invoking MEX files 3 4 L L option flag 7 38 1 option flag 7 38 lasterr function 5 45 lc
133. ges and warnings generated by the MATLAB Compiler Compile time messages are generated during the compile or link phase It is useful to note that most of these compile time error messages should not occur if MATLAB can successfully execute the corresponding M file Run time messages are generated when the executable program runs Use this reference to Confirm that an error has been reported Determine possible causes for an error Determine possible ways to correct an error When using the MATLAB Compiler if you receive an internal error message record the specific message and report it to Technical Support at The MathWorks at supportemathworks com Compile Time Errors p B 2 Error messages generated at compile time Warning Messages p B 11 User controlled warnings generated by the Compiler Run Time Errors p B 18 Errors generated by the Compiler into your code B Eror and Warning Messages B 2 Compile Time Errors Error An error occurred while shelling out to mex mbuild error code errorno Unable to build executable specify the v option for more information The Compiler reports this error if mbuild or mex generates an error Error An error occurred writing to file filename reason The file could not be written The reason is provided by the operating system For example you may not have sufficient disk space available to write the file Error Cannot recompile M file filename because it is already in lib
134. h To work around this limitation simplify the if conditions There is a limitation with the Borland C Compiler In your M code if you use a constant number that includes a leading zero and contains the digit 8 or 9 before the decimal point the Borland compiler will display the error message Error file c line Illegal octal digit in function functionname For example the Borland compiler considers 009 0 an illegal octal integer as opposed to a legal floating point constant which is how it is defined in the ANSI C standard As an aside if all the digits are in the legal range for octal numbers 0 7 then the compiler will incorrectly treat the number as a floating point value So if you have code such as x 007 06 10 and want to use the Borland compiler you should edit the M code to remove the leading zeros and write it as x 7 6 10 2 15 2 installation and Configuration 2 16 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 Lec C Version 2 4 included with MATLAB Microsoft Visual C C Version 5 0 Microsoft Visual C C Version 6 0 Microsoft Visual C C Version 7 0 lccopts bat msvc50opts bat msvc60opts bat msvc7Oopts bat Watcom C
135. h MATLAB 5 0 the name of the basic MATLAB data type Matrix has changed The new name for the data type is mxArray In C beginning with MATLAB 5 0 the name of the basic MATLAB data type mwMatrix has changed The new name for the data type is mwArray Introducing the MATLAB Compiler Limitations and Restrictions MATLAB Code MATLAB Compiler 3 0 supports almost all of the functionality of MATLAB However there are some limitations and restrictions that you should be aware of This version of the Compiler cannot compile Script M files See Converting Script M Files to Function M Files on page 3 10 for further details M files that use objects Calls to the MATLAB Java interface M files that use input or eval to manipulate workspace variables Note input and eval calls that do not use workspace variables will compile and execute properly M files that use exist with two input arguments for example exist foo var The single variable form works for filenames and functions only M files that dynamically name variables to be loaded or saved This example is disallowed by the Compiler x f load foo mat x M files that load text files for example load ascii sampling The Compiler cannot compile built in MATLAB functions functions such as eighave no M file so they can t be compiled Note however that most of these functions are available to you because they are in the MATLAB Math B
136. he program uses mlfPrintMatrix to output the matrices for example mlfPrintMatrix a 4 50 Controlling Code Generation This chapter describes the code generated by the MATLAB Compiler and the options that you can use to control code generation Code Generation Overview p 5 2 Compiling Private and Method Functions p 5 5 The Generated Header Files p 5 8 Internal Interface Functions p 5 11 Supported Executable Types p 5 21 Formatting Compiler Generated Code p 5 35 Including M File Information in Compiler Output p 5 40 Interfacing M Code to C C Code p 5 46 Sample source files and generated filenames Working with private and method functions Generated C and C header files Generated C and C interface functions Generated wrapper functions Controlling the look of generated C C code Controlling annotation in generated C C code Calling C C functions from M code 5 Controlling Code Generation Code Generation Overview Example M Files To generate the various files created by the Compiler this chapter uses several different M files gasket m foo m fun m and sample m Sierpinski Gasket M File function thelmage gasket numPoints GASKET An image of a Sierpinski Gasket IM GASKET NUMPOINTS o ge o Example X 7 gasket 50000 imagesc x colormap O O 0 1 1 1 axis equal tight o ge oe o Copyright c 1984 98 by The MathWorks
137. he MATLAB Compiler that the specified function s will be called through an feval call or through a MATLAB function that accepts a function to feval as an argument or contains an eval string or Handle Graphics Interfacing M Code to C C Code callback that references the specified function Without this pragma the h option will not be able to locate and compile all M files used in your application If you are using the function pragma to define functions that are not available in M code you must write a dummy M function that identifies the number of input and output parameters to the M file function with the same name used on the function line For example s function myfunctionwritteninc This implies that myfunctionwritteninc is an M function that will be called using feval The Compiler will look up this function to determine the correct number of input and output variables Compiling MEX Files If the Compiler finds both a function M file and a mex file in the same directory it will assume that the mex file is the compiled version of the M file In those cases if the M file version is not desired use the mex pragma to force the Compiler to use the MEX file For example function y gamma x mex error gamma MEX file is missing 5 49 5 Controlling Code Generation 5 50 Optimizing Performance The MATLAB Compiler can perform various optimizations on your M file source code that can make the perfo
138. he function By contrast variables used inside script M files are shared with the caller s workspace you can access these variables from the MATLAB interpreter command line The MATLAB Compiler cannot compile script M files nor can it compile a function M file that calls a script Converting a script into a function is usually fairly simple To convert a script to a function simply add a function line at the top of the M file For example consider the script M file houdini m m magic 4 Assign 4x4 matrix to m t m 3 Cube each element of m disp t Display the value of t Running this script M file from a MATLAB session creates variables m and t in your MATLAB workspace The MATLAB Compiler cannot compile houdini m because houdini misa script Convert this script M file into a function M file by simply adding a function header line function m t m magic sz t m 3 disp t houdini sz Assign matrix to m Cube each element of m Display the value of t c o Il oe The MATLAB Compiler can now compile houdini m However because this makes houdini a function running houdini mex no longer creates variable m 3 10 Converting Script M Files to Function Miles in the MATLAB workspace If it is important to have m accessible from the MATLAB workspace you can change the beginning of the function to function m t houdini 3 Working with MEX Files Stand Alone Applications This
139. he optional MATLAB COM Builder you can create COM components that can be used in any application that works with COM objects Hiding Proprietary Algorithms MATLAB M files are ASCII text files that anyone can view and modify MEX files are binary files Shipping MEX files or stand alone applications instead of M files hides proprietary algorithms and prevents modification of your M files Upgrading from Previous Versions of the Compiler Upgrading from Previous Versions of the Compiler MATLAB Compiler 3 0 is fully compatible with previous releases of the Compiler If you have your own M files that were compiled with a previous version of the Compiler and compile them with the new version you will get the same results Upgrading from MATLAB Compiler 2 0 2 1 2 2 2 3 MATLAB Compiler 2 1 and later versions does not support the V1 2 option that was available in Compiler 2 0 Upgrading from MATLAB Compiler 1 0 1 1 In many cases M code that was written and compiled in MATLAB 4 2 will work as is in the MATLAB 6 and the MATLAB 5 series There are however certain changes that could impact your work especially if you integrated Compiler generated code into a larger application Changed Library Name Beginning with MATLAB 5 0 the name of the shared library that contains compiled versions of most MATLAB M file math routines libtbx has changed The new library is now called libmmfile Changed Data Type Names In C beginning wit
140. ibraries To build the shared library libtimefun ext in one step use mcc B csharedlib libtimefun weekday data tic calendar toc This example uses the csharedlib bundle file t W lib filename T link lib h libmmfile mlib The bundle file option B filename ai a2 an replaces the entire expression on the mcc command line with the contents of the specified file and it allows you to use replacement parameters This example uses the csharedlib bundle file and replaces the expression 5 25 5 Controlling Code Generation 5 26 B csharedlib libtimefun with t W lib libtimefun T link lib h libmmfile mlib giving the new statement mcc t W lib libtimefun T link lib h libmmfile mlib weekday data tic calendar toc The t option tells the Compiler to generate C code from each of the listed M files The T link lib option tells the Compiler to compile and link a shared library The h option tells the Compiler to include any other M functions called from those listed on the mcc command line i e helper functions Note You can use the B option with a replacement expression as is at the DOS or UNIX prompt To use B with a replacement expression at the MATLAB prompt you must enclose the expression that follows the B in single quotes when there is more than one parameter passed For example gt gt mcc B csharedlib libtimefun weekday data tic calendar toc can be used as is at the MATLAB prompt because li
141. ibrary For more information about distributing a C application see Distributing Stand Alone Applications on page 4 27 Note On the PC the MATLAB C Math Library is static because the different PC compiler vendors use different C name mangling algorithms 4 Stand Alone Applications Building Stand Alone C C Applications This section explains how to build stand alone C and C applications on UNIX systems and PCs running Microsoft Windows This section begins with a summary of the steps involved in building stand alone C C applications including the mbuild script which helps automate the build process and then describes platform specific issues for both supported platforms Note This chapter assumes that you have installed and configured the MATLAB Compiler Overview On both operating systems the steps you use to build stand alone C and C applications are 1 Verify that mbuild can create stand alone applications 2 Verify that the MATLAB Compiler can link object files with the proper libraries to form a stand alone application Building Stand Alone C C Applications Verify mbuild Verify MATLAB Compiler can generate application Figure 4 1 Sequence for Creating Stand Alone C C Applications shows the sequence on both platforms The sections following the flowchart provide more specific details for the individual platforms Test your mbuild configuration
142. ied on the command line as exported interfaces If additional M files are compiled as a result of being located by the h option they are not included in the exported interface that is produced by the MATLAB Compiler The bundle option B provides a means to replace its expression on the mcc command line with the contents of the specified file Also it lets you include replacement parameters so that any Compiler options that accept names and version numbers will be expanded properly For more information on the bundle option including the available bundle files see B filename a1 a2 an Bundle of Compiler Settings on page 7 41 Note You can use the B option with a replacement expression as is at the DOS or UNIX prompt To use B with a replacement expression at the MATLAB prompt you must enclose the expression that follows the B in single quotes when there is more than one parameter passed For example gt gt mcc B csharedlib libtimefun weekday data tic calendar toc can be used as is at the MATLAB prompt because libtimefun is the only parameter being passed If the example had two or more parameters then the quotes would be necessary as in gt gt mcc B cexcel component class 1 0 weekday data tic calendar toc 5 31 5 Controlling Code Generation 5 32 How mbuild Processes the File Types The mbuild option regsvr uses the mwregsvr32 program to register the resulting shared libra
143. ild and link with MATLAB C C Math Library Enter the number of the options file to use as your default options file If there is more than one options file you can select the one you want by entering its number and pressing Return If there is only one options file available it is automatically copied to your MATLAB directory if you do not already have an mbuild options file If you already have an mbuild options file you are prompted to overwrite the existing one Note The options file is stored in the mat1ab R13 subdirectory of your home directory This allows each user to have a separate mbuild configuration Using the setup option sets your default compiler so that the new compiler is used everytime you use the mbuild script Modifying the Options File Another use of the setup option is if you want to change your options file settings For example if you want to make a change to 4 9 4 Stand Alone Applications 4 10 the current linker settings or you want to disable a particular set of warnings you should use the setup option If you need to change the options that mbuild passes to your compiler or linker you must first run mbuild setup which copies a master options file to your local MATLAB directory typically HOME matlab R13 mbuildopts sh If you need to see which options mbuild passes to your compiler and linker use the verbose option v as in mbuild v filename filename2 to generat
144. ilename Line Column An array for multiple LHS assignment must be a vector If the left hand side of a statement is a multiple assignment the list of left hand side variables must be a vector For example p1 p2 p3 myfunc a Correct p1 p2 p3 myfunc a Incorrect Error File filename Line Column An array for multiple LHS assignment cannot be empty If the left hand side of a statement is a multiple assignment the list of left hand side variables cannot be empty For example p1 p2 p3 myfunc a Correct myfunc a Incorrect B 3 B Eror and Warning Messages B 4 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 pt myfunc a Correct 3 myfunc a Incorrect Error File filename Line Column Expected a variable function or constant found string There is a syntax error in the specified line See the online MATLAB Function Reference pages Error File filename Line Column Expected one of or EOL got string There is a syntax error in the specified line See the online MATLAB Function Reference pages Error File filename Line Column Functions cannot be indexed using or indexing You cannot use the cell array constructor or the structure field access
145. iler may not define all of the global variables Optimized code will not run at all without initialization Generating Files You can use the t option of the Compiler to generate source files in addition to wrapper files For example mcc W main h x m examines x m and all M files referenced by x m but generates only the x main c wrapper file However including the t option in mcc W main h t x m generates x main c x c and all M files referenced by x m 5 21 5 Controlling Code Generation 5 22 MEX Files The W mex L C options produce the MEX file wrapper which includes the mexFunction interface that is standard to all MATLAB plug ins For more information about the requirements of the mex interface see External Interfaces API in the MATLAB documentation In addition to declaring globals and initializing the feval function table the MEX file wrapper function includes interface and definition functions for all M files not included into the set of compiled files These functions are implemented as callbacks to MATLAB Note By default the x option does not include any functions that do not appear on the command line Functions that do not appear on the command line would generate a callback to MATLAB Specify h if you want all functions called to be compiled into your MEX file Main Files You can generate C or C application wrappers that are suitable for building C or C stand alone applicatio
146. iler optimizations to be turned off If you want to have some optimizations on you may specify them after the debug option m Stand Alone CJ Produce a stand alone C application It includes helper functions by default h and then generates a stand alone C wrapper W main In the final stage this option compiles your code into a stand alone executable and links it to the MATLAB C C Math Library T link exe For example to translate an M file named mymfile m into C and to create a stand alone executable that can be run without MATLAB use mcc m mymfile The m option is equivalent to the series of options W main L C t T link exe h libmmfile mlib or B macro option m p Stand Alone C Produce a stand alone C application It includes helper functions by default h and then generates a stand alone C wrapper W main In the final stage this option compiles your code into a stand alone executable and links it to the MATLAB C C Math Library T link exe For example to translate an M file named mymfile m into C and to create a stand alone executable that can be run without MATLAB use mcc p mymfile The p option is equivalent to the series of options W main L Cpp t T link exe h libmmfile mlib or B macro_option_p mcc S Simulink S Function Produce a Simulink S function that is compatible with the Simulink S Function block For example to translate an M file named mymfile m into C and to
147. imizations 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 Optimizations The MATLAB Compiler provides a series of optimizations that can help speed up your compiled code These optimizations are on by default unless you are building a debuggable version Folding Array Constants Folds scalar and nonscalar valued array constants One and Two Dimensional Array Indexing Uses faster routines that are optimized for simple indexing for loops Optimizes for loops with integer starts and increments Introducing the MATLAB Compiler Conditional Expressions Reduces the MATLAB conditional operators to scalar C conditional operators when both operands are known to be integer scalars For more information on these optimizations see Chapter 6 Optimizing Performance mlib Files mlib files make it possible to produce a shared library out of a toolbox and then compile M files that make calls into that toolbox Specifying an m1ib file tells the MATLAB Compiler to link against the mlib file s corresponding shared library whenever it needs to use any of the functions found in that library The mlib file and its corresponding shared library file must be located within the same directory For more information about mlib files see
148. ing MATLAB for Visual Studio directs MSVC to automatically load the add in when you start MSVC again Configuring on Windows 98 and Windows Me Systems Windows 98 To run the MATLAB add in for Visual Studio on Windows 98 systems add this line to your config sys file shell c command com e 32768 p Windows Me To run the MATLAB add in for Visual Studio on Windows Me systems do the following 1 Find C windows system conagent exe in the Windows Explorer 2 Right click on the conagent exe icon 3 Select Properties from the context menu This brings up the CONAGENT EXE Properties window 4 Select the Memory tab in the CONAGENT EXE Properties window 5 Setthe Initial Environment field to 4096 6 Click Apply 7 Click OK For additional information on the MATLAB add in for Visual Studio 4 25 4 Stand Alone Applications 4 26 e See the MATLABAddin hlp file in the lt matlab gt bin win32 directory or Click on the Help icon in the MATLAB add in for Visual Studio toolbar mM er id O Help Icon Packaging Windows Applications for Distribution To distribute a stand alone Windows application you must create a package containing these files e 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 applicatio
149. ion Description arch UNIX Assume local host has architecture arch Possible values for arch include S012 hpux hp700 alpha ibm rs sgi and ginx86 Q response file Windows Replace response file on the mbuild command line with the contents of the text file response file C Compile only Do not link Creates an object file but not an executable D lt name gt Define a symbol name to the C C preprocessor Equivalent to a define lt name gt directive in the source mbuild Table 7 1 mbuild Options Continued Option Description D lt name gt lt value gt D lt name gt lt value gt f lt lt optionsfile gt gt h elp I pathname inline l name L directory Define a symbol name and value to the C C preprocessor Equivalent to a define name value directive in the source UNIX Define a symbol name and value to the C preprocessor Equivalent to a define name value directive in the Source Specify location and name of options file to use Overrides the mbuild default options file search mechanism Create a debuggable executable If this option is specified mbuild appends the value of options file variables ending in DEBUGFLAGS with their corresponding base variable This option also disables the mbuild default behavior of optimizing built object code Help prints a description of mbuild and the list of options
150. ion by editing the corresponding macro_option file bundle file in lt matlab gt toolbox compiler bundles For example to change the x macro edit the file macro_option_x in the bundles directory Setting Up Default Options If you have some command line options that you wish always to pass to mcc you can do so by setting up an mccstartup file Create a text file containing the desired command line options and name the file mccstartup Place this file in one of two directories The current working directory or e Your preferences directory HOME mat1ab R13 on UNIX system root gt profiles lt user gt application data mathworks matlab R13 on PC mcc searches for the mccstartup file in these two directories in the order shown above Ifit 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 7 27 mcc 7 28 command line options Both the mccstartup file and the B option are processed the same way Note If you need to change the meaning of a macro to satisfy your individual requirements you should create or modify your mccstartup file in the preferences directory Changing the file macro option xin the bundles directory changes the option for all Compiler users To see the name of your preferences directory type prefdir at the command prompt Setting a MATLAB Path in the Stand Alone MATLAB Compiler Unlike the MATLAB ver
151. ion table mclSetCurrentLocalFunctionTable amp local function table hello mxArray ans NULL f This is the hello world function written in M code mclMline 3 mclAssignAns amp ans mlfNFprintf O mlfScalar 1 mxCreateString Hello World Ain NULL mxDestroyArray ans mclSetCurrentLocalFunctionTable save local function table mclMlineExitFunction All Annotation To include both comments and source code from the source M file in the generated output use mcc A annotation all or do not stipulate the annotation option thus using the default of a11 This code snippet contains both comments and source code static void Mhello void mclMlineEnterFunction D work hello m hello mexLocalFunctionTable save_local_function_table_ mclSetCurrentLocalFunctionTable amp local function table hello mxArray ans NULL This is the hello world function written in M code fprintf 1 Hello World n x mclMline 3 mclAssignAns amp ans mlfNFprintf O mlfScalar 1 mxCreateString Hello World Ain NULL 5 41 5 Controlling Code Generation 5 42 mxDestroyArray ans mclSetCurrentLocalFunctionTable save local function table mclMlineExitFunction No Annotation To include no source from the initial M file in the generated output use mcc A annotation none This code snippet shows the generated code without comments and source code static void Mhe
152. ion y foo x y 2 pi x If you compile this with the 0 none option you get mlfAssign amp y mclMtimes mlfScalar 6 283185307179586 mclVa x x Compiling with O none O fold scalar mxarrays on gives mlfAssign amp y mclMtimes mxarrayO mclVa x x In the optimized case this code uses mxarrayO which is initialized at program start up to hold the correct value All constants with the same value use the same mxArray variable in the constant pool Nonscalar Arrays fold non scalar mxarrays This optimization is very similar to fold scalar mxarrays It folds nonscalar mxArray values into compile time arrays that are initialized at program start up This can have a large performance impact if you are constructing arrays that use or within a loop This optimization makes the code less readable For example function y test y 10 01 pi pi 2 pi pi 2 Optimizing Arrays If you compile this with the 0 none option you get mlfAssign amp y mclMtimes mlfDoubleMatrix 2 2 _arrayO_ double NULL mlfDoubleMatrix 2 2 _array1_ double NULL Compiling with 0 none O fold non scalar mxarrays on gives mlfAssign amp y _mxarray4_ Scalars fold mxarrays This option is equivalent to using both fold scalar mxarrays and fold non scalar mxarrays It is included for compatibility with P code generation 6 Optimizing Performance Optimizing Loops 6 6 Simple Indexing
153. ivalent to option generates C code T codegen only Places output in specified directory Uses the specified options mex setup and mbuild setup are file filename recommended mcc Table A 1 mcc Quick Reference Continued Option Description Comment Options F option Specifies format parameters option list expression indent n page width n statement indent n g Generates debugging Equivalent to information G A debugline on O none G Debug only Simply turn debugging on so debugging symbol information is included h Compiles helper functions i Causes Compiler to include I directory L language M string o outputfile only M files specified on the command line as exported interfaces Adds new directory to path Generates code that reports file and line numbers on run time errors Specifies output target language Macro to generate a C stand alone application Passes string to mex or mbuild Specifies name location of final executable 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 mate Compiler Quick Reference Table A 1 mcc Quick Reference Continued Option Description Comment Options 0 0 0 0 option on off all none list target number Build an optimized executable Macro to generate a C stand alone application Macro to generate
154. lable Error The option option must be immediately followed by whitespace e g proper example usage These options require additional information so they cannot be combined A B d f F I L M 0 T u W 7X y Y Z For example you can use mcc vc but you cannot use mcc Ac annotation all Error The options specified will not generate any output files Please use one of the following options to generate an executable output file x generates a MEX file executable using C m generates a stand alone executable using C p generates a stand alone executable using C S generates a Simulink MEX S function using C B sgl generates a stand alone graphics library executable using C requires the SGL B sglcpp generates a stand alone graphics library executable using C requires the SGL B pcode generates a MATLAB P code file Or type mcc for more usage information Use one of these options or another option that generates an output file s See MATLAB Compiler Option Flags on page 7 31 or type mcc at the command prompt for more information Compile Time Errors Error The specified file filename cannot be read There is a problem with your specified file For example the file is not readable because there is no read permission Error The option option cannot be combined with other options The V2 0 option must appear separate from other options on the command line For ex
155. lag 7 48
156. le application whose source code consists of mrank m and mrankp c mrank m mrank m contains a function that returns a vector of the ranks of the magic squares from 1 to n function r mrank n r zeros n 1 for k 1 n r k rank magic k end Mixing M Files and C or C The Build Process The steps needed to build this stand alone application are 1 Compile the M code 2 Generate the library wrapper file To perform these steps use mcc t W lib Pkg T link exe h mrank mrankp c libmmfile mlib The MATLAB Compiler generates C source code files named mrank c Pkg c and Pkg h This command invokes mbuild to compile the resulting Compiler generated source files mrank c Pkg c Pkg h with the existing C source file mrankp c and links against the required libraries For details see Building Stand Alone C C Applications on page 4 4 The MATLAB Compiler provides two different versions of mrankp c in the lt matlab gt extern examples compiler directory mrankp c contains a POSIX compliant main function mrankp c sends its output to the standard output stream and gathers its input from the standard input stream mrankwin c contains a Windows version of mrankp c 4 43 4 Stand Alone Applications mbuild does this part mrank m mcc t W lib Pkg T link exe mrank mrankp c Y mrankp c mrank c Pkg c Pkg h C Compiler C Compiler PER RE MS M
157. le and line number information when you receive run time error messages To control code annotation use A option You can combine annotation options for example selecting both comments and line directives The remaining sections focus on the different choices you can use Controlling Comments in Output Code Use the annotation type option to include your initial M file comments and code in your generated C or C output The possible values for type are e all comments none Not specifying any annotation type uses the default of a11 which includes the complete source of the M file comments and code interleaved with the generated C C source The following sections show segments of the generated code from this simple Hello World example function hello This is the hello world function written in M code fprintf 1 Hello World n Note To improve the readability of your generated code turn off optimizations with 0 none or g The examples in this section have optimizations off Including M File Information in Compiler Output Comments Annotation To include only comments from the source M file in the generated output use mcc A annotation comments This code snippet shows the generated code containing only the comments This is the hello inthe middle of the routine static void Mhello void mclMlineEnterFunction D work hello m hello mexLocalFunctionTable save local funct
158. 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 option Formatting Control the formatting of the generated code Table 7 8 Formatting Options shows the available options Table 7 8 Formatting Options Option Description list Generates a table of all the available formatting options expression indent n Sets the number of spaces of indentation for all expressions to n where n is an integer The default indent is 4 7 37 mcc Table 7 8 Formatting Options Continued Option Description page width n Sets maximum width of generated code to n where n is an integer The default width is 80 statement indent n Sets the number of spaces of indentation for all statements to n where n is an integer The default indent is 2 Line Numbers Generate C C code that prints filename and line numbers on run time errors This option flag is useful for debugging but causes the executable to run slightly slower This option is equivalent to mcc A debugline on L language Target Language Specify the target language of the compilation Possible values for language are C or Cpp The default is C Note that these values are case insensitive O option Optimization Options Optimize your M file source code so
159. ll of the conversion between the COM types and MATLAB arrays For details on this conversion see the MATLAB Excel Builder or MATLAB COM Builder documentation 5 33 5 Controlling Code Generation 5 34 Porting Generated Code to a Different Platform The code generated by the MATLAB Compiler is portable among platforms However if you build an executable from foo mon a PC running Windows that same file will not run on a UNIX system For example you cannot simply copy foo mex where the mex extension varies by platform from a PC to a Sun system and expect the code to work because binary formats are different on different platforms all supported executable types are binary However you could copy either all of the generated C code or foo m from the PC to the Sun system Then on the Sun platform you could use mex or mcc to produce a foo mex that would work on the Sun system 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 Formatting Compiler Generated Cod 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 option The remaining sections focus on the different choices you can u
160. llo void mclMlineEnterFunction D work hello m hello mexLocalFunctionTable save_local_function_table_ mclSetCurrentLocalFunctionTable amp local function table hello mxArray ans NULL mciMline 3 mclAssignAns amp ans mlfNFprintf O mlfScalar 1 mxCreateString Hello World n NULL mxDestroyArray ans mclSetCurrentLocalFunctionTable save local function table mclMlineExitFunction Controlling line Directives in Output Code line preprocessing directives inform a C C compiler that the C C code was generated by another tool MATLAB Compiler and they identify the correspondence between the generated code and the original source code M file You can use the line directives to help debug your M file s Most C language debuggers can display your M file source code These debuggers allow you to set breakpoints single step and so on at the M file code level when you use the line directives Use the line setting option to include line preprocessor directives in your generated C or C output The possible values for setting are on off Not specifying any line setting uses the default of off which does not include any line preprocessor directives in the generated C C source Including M File Information in Compiler Output Note When using the line directive the page width directive is disabled in order to make the code work properly with the C debugger Include line Dire
161. lly run the setup option you can reenable your antivirus software Verification of mex Fails If none of the previous solutions addresses your difficulty with mex contact Technical Support at The MathWorks at support amp mathworks com Troubleshooting Troubleshooting the Compiler One problem that might occur when you try to use the Compiler involves licensing Licensing Problem If you do not have a valid license for the MATLAB Compiler you will get an error message similar to the following when you try to access the Compiler Error Could not check out a Compiler License No such feature exists If you have a licensing problem contact The MathWorks A list of contacts at The MathWorks is provided at the beginning of this manual MAILAB Compiler Does Not Generate MEX File If you experience other problems with the MATLAB Compiler contact Technical Support at The MathWorks at support mathworks com 2 27 2 installation and Configuration 2 28 Working with MEX Files This chapter gets you started compiling M files with the MATLAB Compiler A Simple Example The Sierpinski Creating a MEX file from an M file Gasket p 3 2 Compiler Options and Macros p 3 6 Overview of options and macros Generating Simulink S Functions Generating Simulink C MEX S functions p 3 7 Converting Script M Files to Function Converting scripts to functions M Files p 3 10 3 Working with MEX Files 3 2 A
162. ludes the line number information If in your M code you compare against the string value of lasterr you will get different behavior when using this option Since try catch end is not available in g do not use the A debugline on option on Linux when generating a C application 5 45 5 Controlling Code Generation 5 46 Interfacing M Code to C C Code The MATLAB Compiler supports calling arbitrary C C functions from your M code You simply provide an M function stub that determines how the code will behave in M and then provide an implementation of the body of the function in C or C C Example Suppose you have a C function that reads data from a measurement device In M code you want to simulate the device by providing a sine wave output In production you want to provide a function that returns the measurement obtained from the device You have a C function called measure from device that returns a double which is the current measurement collect m contains the M code for the simulation of your application function collect y zeros 1 100 Pre allocate the matrix for i 1 100 y i collect one end function y collect one persistent t if isempty t t 0 end t t 0 05 y sin t The next step is to replace the implementation of the collect_one function with a C implementation that provides the correct value from the device each time it is requested This is accomplished by u
163. m Troubleshooting Troubleshooting the Compiler Typically problems that occur when building stand alone C and C applications involve mbuild However it is possible that you may run into some difficulty with the MATLAB Compiler One problem that might occur when you try to generate a stand alone application involves licensing Licensing Problem 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 If you experience other problems with the MATLAB Compiler contact Technical Support at The MathWorks at support mathworks com Missing Functions In Callbacks If your application includes a call to a function in a callback string or in a string passed as an argument to the feval function or an ODE solver and this is the only place in your M file this function is called the Compiler will not compile the function The Compiler does not look in these text strings for the names of functions to compile See Fixing Callback Problems Missing Functions on page 1 20 for more information 4 35 4 Stand Alone Applications Coding with M Files Only 4 36 One way to create a stand
164. mate Compiler Quick Reference A 2 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 m into C and to create the corresponding Simulink S function using dynamically sized inputs and outputs use mcc S mymfile Create a Stand Alone C Application To translate an M file named mymfile minto C and to create a stand alone executable that can be run without MATLAB use mcc m mymfile Create a Stand Alone C Application 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 p mymfile Create a Stand Alone C Graphics Library Application To translate an M file named mymfile m that contains Handle Graphics functions into C and to create a stand alone executable that can be run without MATLAB use mcc B sgl mymfile Create a Stand Alone C Graphics Library Application To translate an M file named mymfile m that contains Handle Graphics functions into C and to create a stand alone executable that can be run without MATLAB use mcc B sglcpp mymfile Create a C Library To create a C lib
165. me as codegen plus compiles C C files to object form suitable for linking into a shared library DLL Same as compile mex plus links object files into a Simulink S function MEX file Same as compile mexlibrary plus links object files into an ordinary non S function MEX file Same as compile exe plus links object files into a standalone executable Same as compile lib plus links object files into a shared library DLL mex and mexlibrary use the mex script to build a MEX file exe uses the mbuild script to build an executable lib uses mbuild to build a shared library 7 45 mcc v Verbose Display the steps in compilation including The Compiler version number The source filenames as they are processed The names of the generated output files as they are created The invocation of mex or mbuild The v option passes the v option to mex or mbuild and displays information about mex or mbuild w Warning Display warning messages Table 7 12 Warning Option shows the various ways you can use the w option Table 7 12 Warning Option Syntax Description no w option Default displays only serious warnings w list Generates a table that maps lt string gt to warning message for use with enable disable and error Appendix B Error and Warning Messages lists the same information W Enables complete warnings w disable string Disables specific warning associated with l
166. mful effect on your code 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 2 5 2 installation and Configuration shows the preconfigured options files that are included with MATLAB for UNIX Compiler Options File System native ANSI compiler mexopts sh gcc GNU C compiler gccopts sh Information on the options files is provided for those users who may need to modify them to suit their own needs Many users never have to be concerned with the inner workings of the options files Locating Options Files To locate your options file the mex script searches the following The current directory e HOME matlab R13 e lt matlab gt bin mex uses the first occurrence of the options file it finds If no options file is found mex displays an error message Installation MATLAB Compiler To install the MATLAB Compiler on UNIX workstations follow the instructions in the MATLAB Installation Guide for the UNIX platform If you have a license to install the MATLAB Compiler it appears as one of the installation choices that you can select as you proceed through the installation process If the MATLAB Compiler does not appear as one of the installation choices contact The MathWorks to get an updated license file license dat e Via the Web at www mathworks com On the MathWorks home page
167. mlib file indicating that all future references to tic and toc should come from the m1ib files s corresponding shared library When the executable is created it is linked against the shared library For example on the PC the executable timer exe is created and it is linked against libtimefun dll An advantage of using mlib files is that the generated code is smaller because some of the code is now located in the shared library 5 27 5 Controlling Code Generation 5 28 Note On the mcc command line you can access any m1ib file by including the full path to the file For example mcc m timer pathname libtimefun mlib Restrictions UNIX The first three characters of the filename must be lib PC and UNIX You cannot rename the file e PC and UNIX Both the shared library and the mlib file must be in the same directory at compile time PC and UNIX At run time the path to the shared library must be on the system s search path For more information about setting the path on the PC see Shared Libraries on page 4 22 For UNIX information see Locating Shared Libraries on page 4 11 You do not need the mlib file present when running the executable that links to the shared library C Libraries The intent of the C library wrapper files is to allow the inclusion of an arbitrary set of M files into a library The header file contains all of the entry points for all of the compiled M functions Not
168. mporarily Changing the Compiler To temporarily change your C or C compiler use the f option as in mbuild f file The f option tells the mbuild script to use the options file lt file gt If lt file gt is not in the current directory then file must be the full pathname to the desired options file Using the f option tells the mbuild script to use the specified options file for the current execution of mbuild only it does not reset the default compiler 4 21 4 Stand Alone Applications 4 22 Verifying mbuild There is C source code for an example ex1 c included in the lt matlab gt extern examples cmath directory where lt matlab gt represents the top level directory where MATLAB is installed on your system To verify that mbuild is properly configured on your system to create stand alone applications enter at the MATLAB prompt mbuild ex1 c This creates the file called ex1 exe Stand alone applications created on Windows 98 2000 Me or Windows NT always have the extension exe The created application is a 32 bit MS DOS console application Shared Libraries All the libraries WIN32 Dynamic Link Libraries or DLLs for MATLAB the MATLAB Compiler and the MATLAB Math Library are in the directory lt matlab gt bin win32 The DEF files for the Microsoft and Borland compilers are in the lt matlab gt extern include directory All of the relevant libraries for building stand alone applications are WIN3
169. n uses All the MATLAB run time libraries For specific information about packaging these files see Distributing Stand Alone Applications on page 4 27 Distributing Stand Alone Applications Distributing Stand Alone Applications To make packaging an application easier all the necessary MATLAB run time libraries are prepackaged into a single self extracting archive file For more information about how you can use this archive see Packaging the MATLAB Run Time Libraries For information about how customers who receive your application can use this archive see Installing Your Application on page 4 27 Packaging the MATLAB Run Time Libraries All the MATLAB run time libraries required by stand alone applications are prepackaged into a single self extracting archive file called the MATLAB Compiler Run Time Library Installer Instead of including all the run time libraries individually in your stand alone application distribution package you can simply include this archive file The following table lists the name of the archive file for both UNIX and PC systems In the table MATLAB represents your MATLAB installation directory and ARCH represents your UNIX platform Platform MATLAB Compiler Run Time Library Installer UNIX systems lt MATLAB gt extern 1ib lt ARCH gt mglinstaller PCs lt MATLAB gt extern lib win32 mglinstaller exe Installing Your Application To install your application your cu
170. ng from outside of MATLAB In this case the Compiler Does not require MATLAB to be running on the system where the Compiler is running Gives the user a dedicated 30 minute time allotment during which the user has complete ownership over a license to the Compiler Each time a user requests the Compiler the user begins a 30 minute time period as the sole owner of the Compiler license Anytime during the 30 minute segment if the same user requests the Compiler the user gets a new 30 minute allotment When the 30 minute time interval has elapsed if a different user requests the Compiler the new user gets the next 30 minute interval When a user requests the Compiler and a license is not available the user receives the message Error Could not check out a Compiler License This message is given when no licenses are available As long as licenses are available the user gets the license and no message is displayed The best way to guarantee that all MATLAB Compiler users have constant access to the Compiler is to have an adequate supply of licenses for your users 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 execut
171. ns respectively These POSIX compliant main wrappers accept strings from the POSIX shell and return a status code They are meant to translate command like M files into POSIX main applications POSIX Main Wrapper The POSIX main function wrapper behaves exactly the same as the command function duality mode of MATLAB That is any command of the form command argument can also be written in the functional form command argument If you write a function that accepts strings in MATLAB that function will compile to a POSIX main wrapper in such a way that it behaves the same from the DOS UNIX command line as it does from within MATLAB Supported Executable Types The Compiler processes the string arguments passed to the main function and sends them into the compiled M function as strings For example consider this M file sample m function y sample varargin varargin y 0 You can compile sample m into a POSIX main application If you call sample from MATLAB you get sample hello world ans hello ans world ans 0 If you compile sample m and call it from the DOS shell you get C gt sample hello world ans hello ans world C gt The difference between the MATLAB and DOS UNIX environments is the handling of the return value In MATLAB the return value is handled by printing its value in the DOS UNIX shell the return value is handled as the return status code When y
172. ntly work with Microsoft Visual C C Version 7 0 MATLAB Compiler Verification Verifying from MATLAB Once you have verified that you can generate MEX files on your system you are ready to verify that the MATLAB Compiler is correctly installed Type the following at the MATLAB prompt mcc x invhilb After a short delay this command should complete and display the MATLAB prompt Next at the MATLAB prompt type which invhilb The which command should indicate that invhilb is now a MEX file it should have created the file invhilb dll Finally at the MATLAB prompt type invhilb 10 Note that this tests only the Compiler s ability to make MEX files If you want to create stand alone applications or DLLs refer to Chapter 4 Stand Alone Applications Verifying from DOS Command Prompt To verify that the Compiler can generate C MEX files from the DOS command prompt you follow a similar procedure as that used in the previous section 2 23 2 installation and Configuration 2 24 Note Before you test to see if the Compiler can generate MEX files from the DOS command prompt you may want to delete the MEX file you created in the previous section invhilb d11 That way you can be sure your newly generated MEX file is the result of using the Compiler from the DOS prompt To delete this file you must clear the MEX file or quit MATLAB otherwise the deletion will fail Copy invhilb m from the lt matlab gt toolbox m
173. nts You cannot install the MATLAB Compiler unless MATLAB 6 5 Release 13 is already installed on the system The MATLAB Compiler imposes no operating system or memory requirements beyond what is necessary to run MATLAB The MATLAB Compiler consumes a small amount of disk space Table 2 3 Requirements for Creating PC Applications shows the requirements for creating PC applications with the MATLAB Compiler Table 2 3 Requirements for Creating PC Applications To create You need MEX files ANSI C compiler see following note MATLAB Compiler Stand alone C applications ANSI C compiler see following note MATLAB Compiler Stand alone C applications C compiler MATLAB Compiler Note MATLAB includes an ANSI C compiler Lec that is suitable for use with the MATLAB Compiler Note Although the MATLAB Compiler supports the creation of stand alone C applications it does not support the creation of C MEX files 2 installation and Configuration 2 14 Supported ANSI C and C PC Compilers To create C MEX files stand alone C C applications or dynamically linked libraries DLLs with the MATLAB Compiler you must install and configure a supported C C compiler Use one of the following 32 bit C C compilers that create 32 bit Windows dynamically linked libraries DLLs or Windows NT applications Lcc C version 2 4 included with MATLAB This is a C only compiler it does not work with C
174. o see if the Compiler can generate MEX files from the UNIX command prompt you may want to delete the MEX file you created in the previous section invhilb mexsol or whatever the extension is on your system That way you can be sure your newly generated MEX file is the result of using the Compiler from the UNIX prompt Copy invhilb mfrom the matlab toolbox matlab elmat directory to a local directory and then type the following at the UNIX prompt mcc x invhilb 2 installation and Configuration 2 12 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 m invhilb mex c invhilb h invhilb mexsol These are the various files that the Compiler generates from the M file The Compiler generated MEX file appears in the list as the filename followed by the appropriate UNIX MEX file extension In this example the Compiler was executed on Solaris so the Compiler creates the file invhilb mexsol For more information on which files the Compiler creates for a compilation see Chapter 5 Controlling Code Generation To test the newly created MEX file start MATLAB and at the MATLAB prompt type invhilb 10 Microsoft Windows on PCs Microsoft Windows on PCs This section examines the system requirements installation procedures and configuration procedures for the MATLAB Compiler on PCs running Microsoft Windows System Requireme
175. oduce a C shared library using this bundle you would use mcc B csharedlib mysharedlib lt f1 gt lt f2 gt In general each n in the bundle file will be replaced with the corresponding option specified to the bundle file Use to include a character It is an error to have too many or too few options to the bundle file You can place options that you always set in an mccstartup file For more information see Setting Up Default Options on page 7 27 7 41 mcc Note You can use the B option with a replacement expression as is at the DOS or UNIX prompt To use B with a replacement expression at the MATLAB prompt you must enclose the expression that follows the B in single quotation marks For example gt gt mcc B csharedlib libtimefun weekday data tic calendar toc This table shows the available bundle files Bundle File Name Contents ccom cexcel csglcom csglexcel csglsharedlib cppcom cppexcel cppsglcom cppsglexcel cpplib csharedlib macro_default macro_option_g t W com component name class name version T link lib h libmmfile mlib i B excel component name class name version T link lib h libmmfile mlib b i B sgl t W comhg component name class name version T link lib h libmmfile mlib B sgl t W excelhg component name class name version T link lib h libmmfile mlib b i t W libhg shared librar
176. older names user input items in drop down lists Buttons and keys Literal strings in syntax descriptions in reference chapters Mathematical expressions MATLAB output Menu and dialog box titles New terms and for emphasis Omitted input arguments String variables from a finite list Monospace font Monospace font Boldface with book title caps Monospace bold for literals Italics for variables Standard text font for functions operators and constants Monospace font Boldface with book title caps Italics ellipsis denotes all of the input output arguments from preceding syntaxes Monospace italics To assign the value 5 to A enter A 5 The cos function finds the cosine of each array element Syntax line example is MLGetVar ML var name Press the Enter key f fregspace n whole This vector represents the polynomial p x 2x 3 MATLAB responds with A 5 Choose the File Options menu An array is an ordered collection of information c ia ib union sysc d2c sysd method Introducing the MATLAB Compiler This chapter describes the MATLAB Compiler and its uses It also includes new features upgrading information and limitations and restrictions that you should know Introduction p 1 2 A brief overview New Features p 1 4 Features added in this and previous releases Uses of the Compiler p 1 9 High level descriptions of
177. ompiler Run Time Library Installer by double clicking on the mglinstaller exe file Your customers can specify the name of the directory into which they want to install the libraries By default the installer puts the files in the current directory After the installer unpacks and uncompresses the libraries your customers must add the bin win32 subdirectory to the system path variable PATH For example if your customers specify the installation directory mgl runtime dir then they must add mgl_runtime_dir bin win32 to PATH Problem Starting Stand Alone Application Your application may compile successfully but fail when you or one of your customers tries to start it If you run the application from a DOS command window you or one of your customers may see an error message such as Distributing Stand Alone Applications The ordinal could not be located in the dynamic link library dforrt dll To fix this problem locate dforrt dllor dformd dllin your Windows system directory and replace them with the corresponding files in the MATLAB VbinWwin32 directory where MATLAB represents the name of your MATLAB installation directory This same solution works for customers of your application who encounter the same problem Your customers can replace these files in the Windows system directory with the corresponding versions in the lt MGLRUNTIMELIBRARY gt bin win32 directory where lt MGLRUNTIMELIBRARY gt is the name of the
178. on 5 02 6 Borland C C version 5 0 7 Borland C C free command line tools version 5 5 8 Lcc C version 2 4 9 Microsoft Visual C C version 7 0 10 Microsoft Visual C C version 6 0 11 Microsoft Visual C C version 5 0 OR OO CTO OGO 0 None 4 18 Building Stand Alone Applications on PCs Compiler 10 Your machine has a Microsoft Visual C C compiler located at D Applications Microsoft Visual Studio Do you want to use this compiler y n y Please verify your choices Compiler Microsoft Visual C C 6 0 Location D Applications Microsoft Visual Studio Are these correct y n y The default options file C WINNT Profiles username Application Data MathWorks MATLAB R13 compopts bat is being updated Installing the MATLAB Visual Studio add in Updated If the specified compiler cannot be located you are given the message The default location for compiler name is lt directory name gt but that directory does not exist on this machine Use directory name anyway y n Using the setup option sets your default compiler so that the new compiler is used everytime you use the mbuild script Modifying the Options File Another use of the setup option is if you want to change your options file settings For example if you want to make a change to the current linker settings or you want to disable a particular set of warnings you should use the setup option The setup o
179. on indent n This sets the number of spaces of indentation to n an integer and defaults to two spaces of indentation 5 37 5 Controlling Code Generation 5 38 Default Indentation Not specifying indent formatting options uses the default of four spaces for statements and two spaces for expressions For example using mcc xg gasket generates the following code segment 0 1 2 3 4 5 6 7 8 1234567890 123456789012345678901 2345678901 234567890 1234567890 12345678901234567890 void mlxGasket int nlhs mxArray plhs int nrhs mxArray prhs mxArray mprhs 1 mxArray mplhs 1 int i if nlhs 1 mlfError mxCreateString Run time Error File gasket Line 1 Column 1 The function gasket was called with mor e than the declared number of outputs 1 NULL if nrhs 1 mlfError mxCreateString Run time Error File gasket Line 1 Column 1 The function gasket was called with mor e than the declared number of inputs 1 NULL for i 0 i lt 1 i mplhs i NULL for i 0 i lt 1 amp amp i lt nrhs i mprhs i prhs il for i lt 1 i mprhs i NULL mlfEnterNewContext O 1 mprhs 0 mplhs 0 Mgasket nlhs mprhs 0 mlfRestorePreviousContext 0 1 mprhs 0 plhs 0 mplhs 0 Formatting Compiler Generated Cod Modified Indentation This example shows the same segment of code using a statement indentation of t
180. on of rank or mlfRank One way to create a new version of rank is to copy the MATLAB source code for rank and then to edit this copy MATLAB implements rank as the M file rank m rather than as a built in command To see the MATLAB code for rank m enter type rank Copy this code into a file named rank m located in the same directory as mrank mand main m Then modify your version of rank m After completing the modifications compile rank m mcc t rank Compiling rank m generates file rank c which contains a function named mlfRank Then compile the other M files composing the stand alone application mcc t main m produces main c mcc t mrank m produces mrank c mcc W main main mrank rank m produces main_main c To compile and link all four C source code files main c rank c mrank c and main_main c into a stand alone application use 4 40 Alternative Ways of Compiling M Files mcc m main main c main c rank c mrank c The resulting stand alone application uses your customized version of mlfRank rather than the default version of mlfRank stored in the MATLAB M File Math Library Note On PCs running Windows as well as SGI SGI64 and IBM if a function in the MATLAB M File Math Library calls mlfRank it will call the one found in the Library and not your customized version We recommend that you call your version of rank something else for example myrank m Compiling mrank m and rank m as Helper Func
181. on or variable undefined variable or unknown function This warning appears if you refer to a variable but never provide it with a value The most likely cause of this warning is when you call a function that is not on the path or it is a method function Note Inline objects are not supported in this release and will produce this warning when used Warning File filename Line Column The function pragma expects a list of function names pragma_function_missing_names This pragma informs the MATLAB Compiler that the specified function s provided in the list of function names Warning Messages will be called through an feval call This is used so that the h option will automatically compile the selected functions Warning File filename Line Column The call to function functionname on this line passed quantity inputs and the function is declared with quantity2 A run time error will occur if this code is executed too_many_inputs There is an inconsistency between the number of formal and actual inputs to the function Warning File filename Line Column The call to function functionname on this line requested quantity outputs and the function is declared with quantity2 A run time error will occur if this code is executed too many outputs There is an inconsistency between the number of formal and actual outputs for the function Warning File filename Line Column The clear function cannot p
182. onal lines need to be present in the M file mex Purpose mex pragma Syntax mex Description This pragma informs the MATLAB Compiler to select the MEX file over an existing M file If you are using the function pragma to define functions that are not available in M code you should use the external pragma to define the function For example function y gamma x mex error gamma MEX file is missing 7 7 mbchar Purpose Syntax Description Example See Also 7 8 Assert variable is a MATLAB character string mbchar x The statement mbchar x causes the MATLAB Compiler to impute that x is a char matrix At run time if mbchar determines that x does not hold a char matrix mbchar issues an error message and halts execution of the MEX file mbchar tells the MATLAB interpreter to check whether x holds a char matrix If x does not mbchar issues an error message and halts execution of the M file The MATLAB interpreter does not use mbchar to impute x Note that mbchar only tests x at the point in an M file or MEX file where an mbchar call appears In other words an mbchar call tests the value of x only once If x becomes something other than a char matrix after the mbchar test mbchar cannot issue an error message A char matrix is any scalar vector or matrix that contains only the char data type This code in MATLAB causes mbchar to generate an error message because n does not contain a
183. ons 4 48 mxArray a b x y double x pr ROWS COLS 1 2 3 4 5 6 7 8 9 double x pi ROWS COLS 9 2 3 4 5 6 7 8 1 double y pr ROWS COLS 1 2 3 4 5 6 7 8 9 double y pi ROWS COLS 2 9 3 4 5 6 7 1 8 double a pr a pi value of scalar b multpkgInitialize Call multpkg initialization Install a print handler to tell mlfPrintMatrix how to display its output mlfSetPrintHandler PrintHandler Create input matrix x x mxCreateDoubleMatrix ROWS COLS mxCOMPLEX memcpy mxGetPr x x pr ROWS COLS sizeof double memcpy mxGetPi x x pi ROWS COLS sizeof double Create input matrix y y mxCreateDoubleMatrix ROWS COLS mxCOMPLEX memcpy mxGetPr y y pr ROWS COLS sizeof double memcpy mxGetPi y y pi ROWS COLS sizeof double Call the mlfMultarg function a mxArray mlfMultarg amp b x y Display the entire contents of output matrix a mlfPrintMatrix a Display the entire contents of output scalar b mlfPrintMatrix b Deallocate temporary matrices mxDestroyArray a mxDestroyArray b multpkgTerminate Call multpkg termination return 0 Mixing Miles and C or C You can build this program into a stand alone application by using the command mcc t W lib multpkg T link exe multarg multargp c libmmfile mlib The program first displays the cont
184. ons 3 6 7 31 7 49 options summarized A 4 setting path in stand alone mode 7 28 Simulink S function output 7 33 Simulink specific options 3 7 supported executable types 5 21 syntax 7 25 system requirements Microsoft Windows 2 13 UNIX 2 4 troubleshooting 2 27 4 35 verbose output 7 46 warning messages B 1 warnings output 7 46 why compile M files 1 16 MATLAB interpreter 1 3 running a MEX file 1 9 Index 1 6 MATLAB libraries M file Math 4 40 7 44 MATLAB plug ins See MEX wrapper Matrix data type 1 17 mbchar 7 8 mbcharscalar 7 9 mbcharvector 7 10 mbint 7 11 mbintscalar 7 13 mbintvector 7 14 mbreal 7 15 mbrealscalar 7 16 mbrealvector 7 17 mbscalar 7 18 mbuild 4 6 options 7 20 overriding language on PC 4 16 UNIX 4 7 regsvr option 5 32 setup option 4 18 PC 4 18 UNIX 4 8 troubleshooting 4 33 verbose option PC 4 20 UNIX 4 10 verifying PC 4 22 UNIX 4 11 mbuild script PC options 4 23 UNIX options 4 13 mbvector 7 19 mcc 7 25 Compiler 2 3 options A 4 mccpath file 7 28 MCCSAVEPATH 7 28 mccstartup 7 27 method directory 5 5 method function compiling 5 5 mex 5 49 7 7 mex configuring on PC 2 19 overview 1 9 suppressing invocation of 7 43 verifying on Microsoft Windows 2 22 on UNIX 2 10 MEX wrapper 1 9 5 22 MEX file bus error 2 25 comparison to stand alone applications 4 2 compatibility 1 9 computation error 2 25 configuring 2 2 creating on UNIX 2 9 example of creating 3 3 extension Mi
185. or gt lt minor gt W excel lt component_name gt lt class_name gt lt major gt lt minor gt W excelhg lt component_name gt lt class_name gt lt major gt lt minor gt 5 29 5 Controlling Code Generation 5 30 The COM wrapper options create a superset of the files created when producing a C or C library wrapper In addition to the C or C library files the COM wrapper creates the files shown in the following table File Description component name idl idl Interface description file for COM component name com hpp C header file for the COM class component name com cpp C source file for the COM class component name dll cpp DLL interface for the COM object component name def Definition file for the COM DLL component name rc Resource file for the COM DLL If the class name is not specified it defaults to component name If the version number is not specified it defaults to the latest version built or 1 0 if there is no previous version The COM wrapper option creates all the required code and files to create a single COM object that contains all of the compiler generated interfaces It creates a single COM class with the same name as the specified class name and a corresponding interface class called I class name It uses the major and minor version numbers to control the major and minor version numbers of the COM interface that is produced The Compiler
186. ou compile a function into a POSIX main application the first return value from the function is coerced to a scalar and is returned to the POSIX shell 5 23 5 Controlling Code Generation 5 24 Simulink S Functions The W simulink L C options produce a Simulink S function wrapper Simulink S function wrappers conform to the Simulink C S function conventions The wrappers initialize The sizes structure The S function s sample times array The S function s states and work vectors The global variables and constant pool For more information about Simulink S function requirements see Writing S Functions in the Simulink documentation Note By default the S command does not include any functions that do not appear on the command line Functions that do not appear on the command line would generate a callback to MATLAB Specify h if you want all functions called to be compiled into your MEX file C Libraries The intent of the C library wrapper files is to allow the inclusion of an arbitrary set of M files into a static library or shared library The header file contains all of the entry points for all of the compiled M functions The export list contains the set of symbols that are exported from a C shared library Another benefit of creating a library is that you can compile a common set of functions once You can then compile other M functions that depend on them without recompiling the original functions Yo
187. ou may have a problem with your cshrc file When MATLAB launches a new C shell to perform compilations it executes the cshrc script If this script causes unexpected changes to the PATH an error may occur You can test whether this is true by performing a set SHELL bin sh prior to launching MATLAB If this works correctly then you should check your cshrc file for problems setting the PATH Cannot Locate Your Compiler PC If mex has difficulty locating your installed compilers it is useful to know how it goes about finding compilers mex automatically detects your installed compilers by first searching for locations specified in the following environment variables BORLAND for Borland C Compiler Version 5 3 WATCOM for the Watcom C C Compiler MSVCDIR for Microsoft Visual C C Version 5 0 6 0 or 7 0 Next mex searches the Windows registry for compiler entries Note that Watcom does not add an entry to the registry Digital Fortran does not use an environment variable mex only looks for it in the registry Internal Error When Using mex setup PC Some antivirus software packages such as Cheyenne AntiVirus and Dr Solomon may conflict with the mex setup process If you get an error message during mex setup of the following form mex bat internal error in sub get compiler info don t recognize string then you need to disable your antivirus software temporarily and rerun mex setup After you have successfu
188. part of the base installation package but the Fortran shared libraries are on a separate disk called the Associated Products CD MATLAB users running under Digital UNIX should install both the C and Fortran run time shared libraries 4 Stand Alone Applications Note Ifyou distribute an application created with the math libraries on Digital UNIX your users must have both the C and Fortran run time shared libraries installed on their systems 4 14 Building Stand Alone Applications on PCs Building Stand Alone Applications on PCs This section explains how to compile and link the C C code generated from the MATLAB Compiler into a stand alone Windows application This section includes Configuring for C or C on page 4 15 Preparing to Compile on page 4 16 Verifying mbuild on page 4 22 Verifying the MATLAB Compiler on page 4 23 About the mbuild Script on page 4 23 Using an Integrated Development Environment on page 4 23 Distributing Stand Alone Applications on page 4 27 Configuring for C or C mbuild determines whether to compile in C or C by examining the type of files you are compiling Table 4 2 Windows File Extensions for mbuild shows the file extensions that mbuild interprets as indicating C or C files Table 4 2 Windows File Extensions for mbuild Language Extension s C C C Cpp CXX CC If you include both C and C files
189. piles this C source code and the resulting object files are linked against the MATLAB C C Math and Graphics Libraries which are included with the MATLAB Compiler For more information about which libraries must be included when you distribute a C application see Distributing Stand Alone Applications on page 4 27 Developing a Stand Alone Application Suppose you want to create an application that calculates the rank of a large magic square One way to create this application is to code the whole application in C or C however this would require writing your own magic square rank and singular value routines An easier way to create this application is to write it as one or more M files Figure 1 2 Developing a Typical Stand Alone C Application outlines this development process Introducing the MATLAB Compiler mbuild does this part o magic square M File function to find the rank of a C version of M code C File Wrapper C Compiler Shaded block is user written code Shadowed blocks are tools e Unshaded blocks are MATLAB Compiler generated code Dotted blocks are C C compiler generated executables MATLAB M File Math Library MATLAB API Library MATLAB Math Built In Library MATLAB Utility Library ANSI C Library MATLAB C C Graphics Library Linker Stand Alone 0 C Applic
190. ption copies the appropriate options file to your user profile directory To make your user specific changes to the options file you edit your copy of the options file in your user profile directory to correspond to your 4 19 4 Stand Alone Applications 4 20 specific needs and save the modified file This sets your default compiler s options file to your specific version Table 4 3 Compiler Options Files on the PC lists the names of the PC options files included in this release of MATLAB If you need to see which options mbuild passes to your compiler and linker use the verbose option v as in mbuild v filename1 filename2 to generate a list of all the current compiler settings used by mbuild To change the options use an editor to make changes to your options file that corresponds to your compiler You can also embed the settings obtained from the verbose option into an integrated development environment IDE or makefile that you need to maintain outside of MATLAB Often however it is easier to call mouild from your makefile See your system documentation for information on writing makefiles Note Any changes that you make to the local options file compopts bat will be overwritten the next time you run mbuild setup If you want to make your edits persist through repeated uses of mbuild setup you must edit the master file itself The master options files are also located in matlab bin Table 4 3 Compil
191. ptions that do not take arguments by preceding the list of option flags with a single dash for example mcc mg myfun Options that take arguments cannot be combined unless you place the option with its arguments last in the list For example these formats are valid mcc m A full myfun Options listed separately mcc mA full myfun Options combined A option last This format is not valid mcc Am full myfun Options combined A option not last In cases where you have more than one option that takes arguments you can only include one of those options in a combined list and that option must be last You can place multiple combined lists on the mcc command line If you include any C or C filenames on the mcc command line the files are passed directly to mex or mbuild along with any Compiler generated C or C files Using Macros to Simplify Compilation The MATLAB Compiler through its exhaustive set of options gives you access to the tools you need to do your job If you want a simplified approach to 7 25 mcc Table 7 2 Macro Options compilation you can use one simple option i e macro that allows you to quickly accomplish basic compilation tasks If you want to take advantage of the power of the Compiler you can do whatever you desire to do by choosing various Compiler options Table 7 2 Macro Options shows the relationship between the macro approach to accomplish a standard compilation and the mul
192. r mbvector mbintscalar mbintvector mcc mbint Purpose Syntax Description Assert variable is integer mbint n The statement mbint x causes the MATLAB Compiler to impute that x is an integer At run time if mbint determines that x holds a noninteger value the generated code issues an error message and halts execution of the MEX file mbint tells the MATLAB interpreter to check whether x holds an integer value If x does not mbint issues an error message and halts execution of the M file The MATLAB interpreter does not use mbint to impute a data type to x Note that mbint only tests x at the point in an M file or MEX file where an mbint call appears In other words an mbint call tests the value of x only once If x becomes a noninteger after the mbint test mbint cannot issue an error message mbint defines an integer as any scalar vector or matrix that contains only integer or string values For example mbint considers n to be an integer because all elements in n are integers n 57 9 If even one element of n contains a fractional component for example n 57 9 2 then mbint assumes that n is not an integer mbint considers all strings to be integers If nis a complex number then mbint considers n to be an integer if both its real and imaginary parts are integers For example mbint considers the value of n an integer n 4 4 7i mbint does not consider the value of x an integer because one of
193. rary libraryname A procedure already exists in a library that has the same name as the M file that is being compiled For example mcc x sin m Incorrect Error Cannot write file filename because MCC has already created a file with that name or a file with that name was specified as a command line argument The Compiler has been instructed to generate two files with the same name For example mcc W lib liba liba t Incorrect Error Could not check out a Compiler license No additional Compiler licenses are available for your workgroup Error Could not find license file filename Windows only The license dat file could not be found in MATLAB bin Error Could not run mbuild The MATLAB C C Math Library must be installed in order to build stand alone applications Install the MATLAB C C Math Library Error File filename not found A specified file could not be found on the path Verify that the file exists and that the path includes the file s location You can use the I option to add a directory to the search path Error File filename is a script M file which cannot be compiled with the current Compiler The MATLAB Compiler cannot compile script M files To learn how to convert script M files to function M files see Converting Script M Files to Function M Files on page 3 10 Error File filename Line Column is not a MATLAB operator Use instead Use the MATLAB relational operator not
194. rary use mcc m W lib libfoo T link lib foo m Common Uses of the Compiler Create a C Library To create a C library use mcc p W lib libfoo T compile lib foo m Create a C Shared Library To create a C shared library that performs specialized calculations that you can call from your own programs use mcc W lib mylib L C t T link lib h Function1 Function2 Create MATLAB P Code To translate an M file named mymfile minto MATLAB P code use mcc B pcode mymfile Note You can add the g option to any of these for debugging purposes A mate Compiler Quick Reference mcc Bold entries in the Comment Options column indicate default values Table A 1 mcc Quick Reference Option Description Comment Options A annotation type Controls M file type all code comment inclusion in comments generated C C source none A debugline setting Controls the inclusion of setting on source filename and line off numbers in run time error messages A line setting Controls the line setting on preprocessor directives off B f filename directory filename included in the generated C C source Generates a Visual Basic file containing the Microsoft Excel Formula Function interface to the Compiler generated COM object Replaces B filename on The file should contain only mcc the mcc command line with command line options the contents of filename When used with a macro Overrides T option equ
195. rator by itself as an array index For example A 5 is okay but y is not Error File filename Line Column The variable variablename was mentioned more than once as an input The argument list has a repeated variable For example function y myfun x x Incorrect Error File filename Line Column The variable variablename was mentioned more than once as an output The return value vector has a repeated variable For example function x x myfun y Incorrect Error File filename Line Column This statement is incomplete Variable arguments cannot be made global or persistent The variables varargin and varargout are not like other variables They cannot be declared either global or persistent For example global varargin Incorrect Error File filename Line Column Variable argument varargin must be last in input argument list The function call must specify the required arguments first followed by varargin For example function out1 out2 examplei a b varargin Correct function out1 out2 example1 a varargin b Incorrect Error File filename Line Column Variable argument varargout must be last in output argument list The function call must specify the required arguments first followed by varargout For example function i j varargout ex2 x1 y1 x2 y2 val Correct function i varargout j ex2 x1 y1 x2 y2 val Incorrect Error File filename Lin
196. rmance of the generated C C code much faster than the performance of the M code in the MATLAB interpreter MATLAB Compiler 3 0 provides a series of optimizations that can help speed up your compiled code This chapter describes the optimization options The only times you would choose not to optimize are if you are debugging your code or you want to maintain the readability of your code Optimization Bundles p 6 2 Bundles that allow you to select the most common optimization options Optimizing Arrays p 6 4 Improving the performance of code that manipulates scalar arrays Optimizing Loops p 6 6 Improviing the performance of simple one and two dimensional array index expressions Optimizing Conditionals p 6 9 Reducing the MATLAB conditional operators to scalar C conditional operators Optimizing MATLAB Arrays p 6 10 Accelerates scalar math operations 6 Optimizing Performance Optimization Bundles 6 2 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 lt filename gt lt al gt lt a2 gt lt an gt Bundle of Compiler Settings on page 7 41 Turn On All Optimizations To turn on all optimizations use 0 all This bundle is stored in matlab toolbox compiler bundles op
197. rocess the optionname argument in compiled code clear cannot handle flag You cannot use clear variables clear mex clear functions or clear all in compiled M code Warning File filename Line Column The clear statement did not specifically list the names of variables to be cleared as constant strings A run time error will be reported if this code is executed clear_non_constant_strings Use one of the forms of the clear command that contains the names of the variables to be cleared Use clear name or clear name do not use clear name Warning File filename Line Column The Compiler does not support the optionname option to save This option is ignored save option ignored You cannot use ascii double or tabs with the save command in compiled M code Warning File filename Line Column The filename provided to load save was a cell array or structure index that could possibly expand into a comma separated list An error will occur at run time if a comma list is present for the filename load save filename The Compiler needs to know statically the number of variables that are involved in a load or save If a cell array is involved the Compiler cannot make that determination and the generated code may behave differently from MATLAB Warning File filename Line Column The functionname function is only available in MEX mode A run time error will occur if this code is executed in stand alone mod
198. rom the Help browser Error File filename Line Column The end operator can only be used within an array index expression You can use the end operator in an array index expression such as sum A end You cannot use the end operator outside of such an expression for example y 1 end Error File filename Line Column The name parametername occurs twice as an input parameter The variable names specified on the function declaration line must be unique For example function foo bar1 bar2 Correct function foo bar bar Incorrect Error File filename Line Column The name parametername occurs twice as an output parameter The variable names specified on the function declaration line must be unique For example function bar1 bar2 foo Correct function bar bar I foo Incorrect Error File filename Line Column The operatorname operator may only produce a single output The primitive operator produces only a single output For example X 7 1 10 Correct x y 1 10 Incorrect B Eror and Warning Messages B 6 Error File filename Line Column The PERSISTENT declaration must precede any use of the variable variablename In the text of the function there is a reference to the variable before the persistent declaration Error File filename Line Column The single colon operator can only be used within an array index expression You can only use the ope
199. rrors 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 m which in MATLAB would produce the error message Inner matrix dimensions must agree function tmmult a ones 2 3 b ones 4 5 y mmult a b function y mmult a b y a b If you create a Compiler generated MEX file with the command mcc x tmmult and run it your results are tmmult Error using gt Inner matrix dimensions must agree Error in gt lt matlab gt toolbox compiler mmult m On line 2 gt y a b Error using gt Inner matrix dimensions must agree Error in gt lt matlab gt toolbox compiler tmmult d11 The information about where the error occurred is not available However if you compile tmmult m and use the A debugline on option as in mcc x A debugline on tmmult 5 44 Including M File Information in Compiler Output your results are Error using tmmult Error using gt Inner matrix dimensions must agree Error in File lt matlab gt extern examples compiler tmmult m Function tmmult Line 4 Note When using the A debugline on option the lasterr function returns a string that inc
200. rted from a C shared library but the Compiler supports both C and C code generation in producing COM objects mbuild automatically Invokes the Microsoft Interface Definition Language MIDL compiler nvokes the resource compiler Specifies the DEF files Using mbuild options you can enable auto registration of the COM compatible DLL Note Creating Excel plug ins from MATLAB M files is available on Windows only The only compilers that support the building of Excel plug ins with the MATLAB Compiler are Borland C Builder versions 3 0 4 0 and 5 0 and Microsoft Visual C C versions 5 0 6 0 and 7 0 For example to compile plusi m into an Excel plug in use mcc B cexcel addin addin 1 0 plusi m For more information see the MATLAB Excel Builder documentation Troubleshooting Troubleshooting Troubleshooting mbuild This section identifies some of the more common problems that might occur when configuring mbuild to create stand alone applications Options File Not Writeable When you run mbuild setup mbuild makes a copy of the appropriate options file and writes some information to it If the options file is not writeable you are asked if you want to overwrite the existing options file If you choose to do so the existing options file is copied to a new location and a new options file is created Out of Environment Space Running mex or mbuild On Windows 98 systems the mex and mbuild scripts requir
201. ry at the end of compilation The Compiler uses this option whenever it produces a COM wrapper file lt filename gt idl You can specify IDL source files on the mbuild command line These files are compiled using the MIDL Compiler The compiler adds any generated idl files to the mbuild command line lt filename gt def You can specify DEF files on the mbuild command line to indicate the symbols exported from a given shared library It is an error to have more than one def file specified on the command line filename rc You can specify an RC file on the MATLAB Compiler command line and it is added into the DLL as required It is an error to have more than one rc file specified on the command line COM Signature When using the MATLAB Compiler and its COM wrapper option with an M file the Compiler produces and registers a COM compatible DLL The Compiler produces the necessary function calls in accordance with these signatures M Function Signature Y1 Y2 Varargout f X1 X2 Varargin Supported Executable Types C Signature void mlxF int nlhs mxArray plhs int nrhs const mxArray prhs mxArray mlfNF int nargout mxArray y1 mxArray y2 mxArray x1 mxArray x2 COM IDL Signature HRESULT f in long nargout in out VARIANT Y1 in out VARIANT Y2 in out VARIANT varargout in VARIANT X1 in VARIANT X2 in VARIANT varargin The COM run time performs a
202. s x ELE Output Argument Processing return theImage NF Interface Function The Compiler produces this interface function only when the M function uses the variable nargout The nargout interface allows the number of requested outputs to be specified via the nargout argument as opposed to the normal interface that dynamically calculates the number of outputs based on the number of non NULL inputs it receives This is the corresponding NF interface function NFoo for the foo m example described earlier in this chapter This function calls the Mfoo function appearing in foo cpp LI LI LI LI LI The function Nfoo contains the nargout interface for the foo M function from file lt matlab gt extern examples compiler foo m lines 1 8 This interface is only produced if the M function uses the special variable nargout The nargout interface allows the number of requested outputs to be specified via the nargout argument as opposed to the normal interface which dynamically calculates the number of outputs based on the number of non NULL inputs it receives This function processes any input arguments and passes them to the implementation version of the Internal Interface Functions function appearing above mwArray Nfoo int nargout mwArray b mwArray x mwArray y I e Input Argument Processing mwArray a mwArray UNDEFINED mwArray b
203. s not match the known signature for this function known number of inputs quant found number of inputs quant2 known number of outputs quantTfound number of outputs quant2 known varargin used quant found varargin used quant2 known varargout used quant1 found varargout used quant2 known nargout used quant found nargout used quant2 builtin_signature_mismatch When compiling an M file that is contained in the MathWorks libraries the number of inputs outputs and the signatures to the function must match exactly Warning The file filename was repeated on the Compiler command line repeated_file This warning occurs when the same filename appears more than once on the compiler command line For example mcc x sample m sample m Will generate the warning Warning Messages Warning The name of a shared library should begin with the letters lib libraryname doesn t missing lib sentinel This warning is generated if the name of the specified library does not begin with the letters lib This warning is specific to UNIX and does not occur on Windows For example mcc t W lib liba T link lib aO a1 No warning mcc t W lib a T link lib a0 al Will generate a warning Warning The option optionname is ignored in modename mode specify for help switch_ignored Modename 1 2 or 2 0 Certain options only have meaning in one or the other mode For example if you use the e option you can t use the
204. s sets your default compiler s options file to your specific version Temporarily Changing the Compiler To temporarily change your C or C compiler use the f option as in mex f file The f option tells the mex script to use the options file lt file gt If file is not in the current directory then file must be the full pathname to the desired options file Using the f option tells the mex script to use the specified options file for the current execution of mex only it does not reset the default compiler Creating MEX Files To create MEX files on UNIX first copy the source file s to a local directory and then change directory cd to that local directory 2 9 2 installation and Configuration 2 10 On UNIX MEX files are created with platform specific extensions as shown in Table 2 2 MEX File Extensions for UNIX Table 2 2 MEX File Extensions for UNIX Platform MEX File Extension Dec Compaq Alpha mexaxp HP 9000 PA RISC mexhp7 HP UX mexhpux IBM RS 6000 mexrs6 Linux mexglx SGI mexsg Solaris mexsol The lt matlab gt extern examples mex directory contains C source code for the example yprime c After you copy the source file yprime c to a local directory and cd to that directory enter at the MATLAB prompt mex yprime c This should create the MEX file called yprime with the appropriate extension corresponding to your UNIX platform For example if you create the MEX file on
205. s sin v and v is known to be double and scalar this optimization uses the scalar double sin function This optimization is always on when compiling to C C and cannot be disabled It is provided for compatibility with P code generation Scalar Doubles speculate This optimization is similar to the technology used by MATLAB to accelerate scalar double math operations It makes educated guesses about the type of MATLAB arrays and optimizes the code accordingly This optimization can have dramatic impact on scalar double MATLAB code and more modest impact on small array operations This optimization is off by default 6 10 Reference 7 Reference 7 2 Functions By Category Pragmas S external function mex Call arbitrary C C functions feval pragma Prefer the MEX file over an existing M file Compiler Functions mbchar mbcharscalar mbcharvector mbint mbintscalar mbintvector mbreal mbrealscalar mbrealvector mbscalar mbvector Command Line mbuild mcc MATLAB Compiler Options Flags Macro Options Impute char matrix Impute character scalar Impute char vector Impute integer Impute integer scalar Impute integer vector Impute real Impute real scalar Impute real vector Impute scalar Impute vector Tools Customize building and linking Invoke MATLAB Compiler Overview of Compiler options Simplify basic compilation tasks Code Generation Control Compiler o
206. s the results function main r mrank 5 To compile these into code that can be built into a stand alone application invoke the MATLAB Compiler mcc mc main mrank Coding with M Files Only The m option flag causes the MATLAB Compiler to generate C source code suitable for stand alone applications For example the MATLAB Compiler generates C source code files main c main main c and mrank c main_main c contains a C function named main main c and mrank c contain a C functions named mlfMain and mlfMrank The c option flag inhibits invocation of mbuild To build an executable application you can use mbuild to compile and link these files Or you can automate the entire build process invoke the MATLAB Compiler twice use mbuild to compile the files with your ANSI C compiler and link the code by using the command mcc m main mrank Figure 4 2 Building Two M Files into a Stand Alone C Application illustrates the process of building a stand alone C application from two M files The commands to compile and link depend on the operating system being used See Building Stand Alone C C Applications on page 4 4 for details 4 37 4 Stand Alone Applications main m mrank m mcc W main t main mcc t mrank m Vv V mbuild does main main c main c mrank c this part C Compiler C Compiler panne a unt eee eed 2 S MIA Ca ner Object File
207. se Note To improve the readability of your generated code turn off optimizations with 0 none or g The examples in this section have optimizations off Listing All Formatting Options To view a list of all available formatting options use mcc F list Setting Page Width Use the page width n option to set the maximum width of the generated code ton aninteger The default is 80 columns wide so not selecting any page width formatting option will automatically limit your columns to 80 characters Setting the page width to a desired value does not guarantee that all generated lines of code will not exceed that value There are cases where due to indentation perhaps a variable name may not fit within the width limit Since variable names cannot be split they may extend beyond the set limit Also to maintain the syntactic integrity of the original M source annotations included from the M source file are not wrapped Note When using A line on which is the default with the MATLAB add in for Visual Studio the page width is set as large as possible to support source level debugging and this setting is ignored 5 35 5 Controlling Code Generation Default Width Not specifying a page width formatting option uses the default of 80 Using mcc xg gasket generates this code segment 0 1 2 3 4 5 6 7 8 12345678901234567890123456789012345678901234567890123456789012345678901234567890 for mclForStart amp viter__
208. sing the s external pragma The external pragma informs the MATLAB Compiler that the implementation version of the function Mf will be hand written and will not be generated from the M code This pragma affects only the single function in which it appears Any M function may contain this pragma local global 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 s external pragma This header file will contain the extern declaration of the function that the user must provide This function must conform to the same interface as the Compiler generated code The Compiler will still generate a c or cpp file from the m file in question The Compiler will generate the feval table which includes the function and all of the required interface functions for the M function but the body of M code from that function will be ignored It will be replaced by the hand written code The Compiler will generate the interface for any functions that contain the external pragma into a separate file called file _external h or file external hpp The Compiler generated C or C file will include this header file to get the declaration of the function being provided In this example place the pragma in the collect_one local function function collect y zeros 1 100
209. sion of the Compiler which inherits MATLAB path from MATLAB the stand alone version has no initial path If you want to set up a default path you can do so by making an mccpath file To do this 1 Create a text file containing the text I your directory here for each directory you want on the default path and name this file mccpath Alternately you can call the mccsavepath M function from MATLAB to create an mccpath file 2 Place this file in your preferences directory To do so run the following commands at the MATLAB prompt cd prefdir mccsavepath These commands save your current MATLAB path to a file named mccpath in your user preferences directory Type prefdir to see the name of your preferences directory The stand alone version of the MATLAB Compiler searches for the mccpath file in your current directory and then your preferences directory If it finds an mccpath file it processes the directories specified within the file and uses them to initialize its search path Note that you may still use the I option on the command line or in mccstartup files to add other directories to the search path Directories specified this way are searched after those directories specified in the mccpath file mcc Conflicting Options on Command Line If you use conflicting options the Compiler resolves them from left to right with the rightmost option taking precedence For example using the equivalencies in Table 7 2 Ma
210. stomers must Run the MATLAB Compiler Run Time Library Installer This program extracts the libraries from the archive and installs them in subdirectories of a directory specified by the user e Add the bin lt ARCH gt subdirectory to their path This is the only MATLAB Compiler Run Time Library subdirectory that needs to be added to the path 4 27 4 Stand Alone Applications 4 28 Note If customers already have the MATLAB math and graphics run time libraries installed on their system they do not need to reinstall them They only need to ensure that the library search path is configured correctly On UNIX Systems On UNIX systems your customers run the MATLAB Compiler Run Time Library Installer by executing the mglinstaller command at the system prompt Your customers can specify the name of the directory into which they want to install the libraries By default the installer puts the files in the current directory After the installer unpacks and uncompresses the libraries your customers must add the name of the bin lt ARCH gt subdirectory to the LD_LIBRARY_PATH environment variable The equivalent variable on HP UX systems is the SHLIB_PATH and LIBPATH on IBM AIX systems For example if customers working on a Linux system specify the installation directory ng1 runtime dir then they must add mgl runtime dir bin glnx86 to the LD LIBRARY PATH environment variable On PCs On PCs your customers run the MATLAB C
211. t bundle all By default all optimizations except speculate are on unless you specifically disable them or use the g option for debugging The g option disables all optimizations Turn Off All Optimizations To turn off all optimizations use 0 none This bundle is stored in matlab toolbox compiler bundles opt bundle none This optimization setting is used whenever you use g for debugging Turn On Individual Optimizations You can enable or disable each individual optimization To enable disable an optimization use O optimization option on off where optimization option is array indexing fold mxarrays fold non scalar mxarrays fold scalar mxarrays optimize conditionals Optimization Bundles optimize integer for loops percolate simple types speculate List All Optimizations To list all available optimizations use 0 list 6 3 6 Optimizing Performance Optimizing Arrays 6 4 Scalar Arrays fold scalar mxarrays When this optimization is enabled all constant scalar valued array operations are folded at compile time and are stored in a constant pool that is created once at program initialization time Folding reduces the number of computations that are performed at run time thus improving run time performance Scalar folding can dramatically improve the performance of code that is manipulating scalar arrays but it makes the code less readable For example funct
212. t string gt Appendix B Error and Warning Messages lists the valid lt string gt values Leave off the optional lt string gt to apply the disable action to all warnings 7 46 mcc Table 7 12 Warning Option Continued Syntax Description w enable lt string gt Enables specific warning associated with lt string gt Appendix B Error and Warning Messages lists the valid lt string gt values Leave off the optional lt string gt to apply the enable action to all warnings w error string Treats specific warning associated with lt string gt as error Leave off the optional lt string gt to apply the error action to all warnings Y lt license dat File Use license information in license dat file when checking out a Compiler license mbuild mex Options f filename Specifying Options File Use the specified options file when calling mex or mbuild This option allows you to use different compilers for different invocations of the MATLAB Compiler This option is a direct pass through to the mex or mbuild script See External Interfaces API in the MATLAB documentation for more information about using this option with the mex script Note Although this option works as documented we suggest that you use mex setup or mbuild setup to switch compilers G Debug Only Cause mex or mbuild to invoke the C C compiler with the appropriate C C compiler options for
213. t the end of the mcc command line d directory Output Directory Place the output files from the compilation in the directory specified by the d option h Helper Functions Compile helper functions Any helper functions that are called will be compiled into the resulting MEX or stand alone application The m option automatically compiles all helper functions so m effectively calls h Using the h option is equivalent to listing the M files explicitly on the mcc command line 7 43 mcc 7 44 The h option purposely does not include built in functions or functions that appear in the MATLAB M File Math Library portion of the C C Math Libraries This prevents compiling functions that are already part of the C C Math Libraries If you want to compile these functions as helper functions you should specify them explicitly on the command line For example use mcc m minimize it fminsearch instead of mcc m h minimize it i Include Exported Interfaces Cause the Compiler to include only the M files that are specified on the command line as exported interfaces If additional M files are compiled as a result of being located by the h option they are not included in the exported interface that is produced by the MATLAB Compiler I directory Directory Path Add a new directory path to the list of included directories Each I option adds a directory to the end of the current search path For example
214. ted Files shows the names of the files generated when you compile a generic M file Table 5 1 file m for the MEX and stand alone targets The table also shows the files generated when you compile a set of files filelist for the library target and the COM target 5 Controlling Code Generation 5 4 Table 5 1 Compiler Generated Files C C Header file h file hpp Code file c file cpp Main Wrapper file main c file main cpp W main MEX Wrapper file mex c N A C W mex MEX files are not supported Simulink Wrapper file_simulink c N A C W simulink Library W lib filelist COM Component MEX files are not supported filelist c filelist cpp filelist h filelist hpp filelist exports filelist mlib filelist mlib compname idl idl compname idl idl W com compname classname major minor compname com hpp compname com hpp W comHG compname classname major minor compname com cpp compname com cpp compname dll cpp compname dll cpp compname def compname def compname rc compname rc Note Many of the code snippets generated by the MATLAB Compiler that are used in this chapter use the F page width option to produce readable code that fits nicely on the book s printed page For more information about the page width option see Formatting Compiler Generated Code on page 5 35 Compiling Private and Method Functions Compiling Private and Method Functions Private functions are
215. tement did not specifically list the names of variables to be loaded as constant strings Use one of the forms of the 1oad command that contains the names of the variables to be loaded for example load filename num value Run time Error File filename Line Column The save statement did not specifically list the names of variables to be saved as constant strings Use one of the forms of the save command that contains the names of the variables to be saved for example save testdata num value B 19 B Eror and Warning Messages B 20 Symbols line directives 5 42 external 7 5 function 7 6 mex 7 7 mex pragma 7 7 cshrc 4 11 DEF file 4 22 A A option flag 7 35 add in MATLAB for Visual Studio 4 23 adding directory to path I option flag 7 44 algorithm hiding 1 16 annotating A option flag 7 35 code 5 40 7 35 output 7 35 ANSI compiler installing on Microsoft Windows 2 17 installing on UNIX 2 7 application POSIX main 5 22 application coding with M files and C C files 4 42 M files only 4 36 array_indexing optimization 6 6 axes objects 1 21 B B ccom option flag 7 33 B cexcel option flag 7 33 B cppcom option flag 7 34 B cppexcel option flag 7 34 B cpplib option flag 7 34 B cppsglcom option flag 7 34 B cppsglexcel option flag 7 34 B csglcom option flag 7 33 B csglexcel option flag 7 34 B csglsharedlib option flag 7 34 B csharedlib option flag 7 35 b option 7 41 B option fla
216. ternal 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 C Interface Functions The C interface functions process any input arguments and pass them to the implementation version of the function Mf mlxF Interface Function The Compiler always generates the m1xF interface function which is used by feval At times the Compiler needs to use feval to perform argument matching even if the user does not specifically call feval For example X cell 1 5 y 12345 x 3 deal y would use the feval interface The following C code is the corresponding feval interface mlxGasket from the Sierpinski Gasket example This function calls the C Mgasket function Note Comments have been added to the generated code to highlight where the input and output arguments are processed and where functions are called The function mlxGasket contains the feval interface for the gasket M function from file lt matlab gt extern examples compiler gasket m lines 1 23 The feval function calls the implementation version of gasket through this function This function pro
217. th a dynamically sized number of inputs and outputs That is you can pass any number of inputs and outputs in or out of the S function Both the MATLAB Fen block and the S Function block are single input single output blocks Only one line can be connected to the input or output of these blocks However each line may be a vector signal essentially giving these blocks multi input multi output capability To generate a C language S function of this type from an M file use the S option mcc S mfilename Note The MATLAB Compiler option that generates a C language S function is a capital S S 3 Working with MEX Files The result is an S function described in the following files mfilename c mfilename h mfilename simulink c mfilename ext where ext is the MEX file extension for your platform e g d11 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 These options specifically set the number of inputs u and the number of outputs y for your function If either u or y is omitted the respective input or output will be dynamically sized mcc S u 1 y 2 mfilename In the above line the S function will be generated with an input vector whose width is 1 and an output vector whose with is
218. the parts the imaginary has a fractional component mbint X74 7 51 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 gt mbint Argument to mbint must be integer See Also mbintscalar mbintvector mcc 7 12 mbintscalar Purpose Syntax Description Example See Also Assert variable is integer scalar mbintscalar n The statement mbintscalar x causes the MATLAB Compiler to impute that x is an integer scalar At run time if nbintscalar determines that x holds a value other than an integer scalar mbintscalar issues an error message and halts execution of the MEX file mbintscalar tells the MATLAB interpreter to check whether x holds an integer scalar value If x does not mbintscalar issues an error message and halts execution of the M file The MATLAB interpreter does not use mbintscalar to impute x Note that mbintscalar only tests x at the point in an M file or MEX file where an mbintscalar call appears In other words an mbintscalar call tests the value of x only once If x becomes a vector after the mbintscalar test mbintscalar cannot issue an error message mbintscalar defines an integer scalar as any value that meets the criteria of both mbint and mbscalar This code in MATLAB causes mbintscalar to generate an error message because although n is a scalar n does not hold an integer value
219. tion and then see which M file the Compiler parses The v option prints the full pathname to the M file Note The Compiler produces a warning specified_file_mismatch if a file with a full pathname is included on the command line and it finds it somewhere else Compiling Embedded M Files If the M file you are compiling calls other M files you can list the called M files on the command line Doing so causes the MATLAB Compiler to build all the M files into a single MEX file which usually executes faster than separate MEX files Note however that the single MEX file has only one entry point regardless of the number of input M files The entry point is the first M file on the command line For example suppose that be11 m calls watson m Compiling with mcc x bell watson creates bell mex The entry point of bell mex is the compiled code from bell m The compiled version of be11 m can call the compiled version of watson m However compiling as mcc x watson bell creates watson mex The entry point of watson mex is the compiled code from watson m The code from bell m never gets executed As another example suppose that x m calls y m and that y mcalls z m In this case make sure that x m is the first M file on the command line After x m it does not matter which order you specify y m and z m mcc MATLAB Compiler Option Flags The MATLAB Compiler option flags perform various functions that affect the generated code
220. tions Another way of building the mrank stand alone application is to compile rank m and mrank m as helper functions to main m In other words instead of invoking the MATLAB Compiler three separate times invoke the MATLAB Compiler only once For C mcc m main rank For C mcc p main rank These commands create files containing the C or C source code The macro options m and p automatically compile all helper functions 4 41 4 Stand Alone Applications Mixing M Files and C or C 4 42 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 To write a stand alone application this way you must know how to Call the external C or C functions generated by the MATLAB Compiler Handle the results these C or C functions return Note If you include compiled M code into a larger application you must produce a library wrapper file even if you do not actually create a separate library For more information on creating libraries see the library sections in Supported Executable Types on page 5 21 Simple Example This example involves mixing M files and C code Consider a simp
221. tioption alternative Macro Bundle File Creates Option Equivalence Option Translate M to C C Function Wrapper Target Language Output Stage Helper Functions ei M File Library d m macro option m Stand alone C t W main L C T link exe h libmmfile mlib application p macro_option_p Stand alone t W main L Cpp T link exe h libmmfile mlib C application X macro_option_x MEX function t W mex LC T link mexlibrary libmatlbmx mlib S macro_option_S Simulink t W simulink L C T link mex libmatlbmx mlib S function g macro_option_g Enable debug G A debugline on 0O none 7 26 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 mcc Table 7 3 m Macro shows the options that compose the m macro and the information that they provide to the Compiler Table 7 3 m Macro Option Function t Translate M code to C C code W main Produce a wrapper file suitable for a stand alone application L C Generate C code as the target language T link exe Create an executable as the output h Automatically find and compile helper functions included in the source M file libmmfile mlib Link to this shared library whenever necessary Changing Macro Options You can change the meaning of a macro opt
222. to the ans variable it deallocates the output This function processes any input arguments and passes them to the implementation version of the function appearing above void Vfoo mwArray x mwArray y ProBoats SS Input Argument Processing mwArray a mwArray UNDEFINED mwArray b mwArray UNDEFINED were ee eee eee eee Call M Function a Mfoo amp b O x y Supported Executable Types Supported Executable Types Wrapper functions create a link between the Compiler generated code and a supported executable type by providing the required interface that allows the code to operate in the desired execution environment The wrapper functions differ depending on the execution environment whereas the C and C header files and code that are generated by the Compiler are the same for MEX functions stand alone applications and libraries To provide the required interface the wrapper Defines persistent global variables Initializes the feval function table for run time feval support Performs wrapper specific initialization and termination nitializes the constant pools generated by optimization This section discusses the various wrappers that can be generated using the MATLAB Compiler Note When the Compiler generates a wrapper function it must examine all ofthe m files that will be included into the executable If you do not include all the files the Comp
223. turns a pointer to an mxArray variable named R The easiest way to display the contents of R is to call the mlfPrintMatrix convenience function mlfPrintMatrix R Mixing M Files and C or C mlfPrintMatrix is one of the many routines in the MATLAB Math Built In Library which is part of the MATLAB Math Library Finally mrankp must free the heap memory allocated to hold matrices and call the Compiler generated termination function mxDestroyArray N mxDestroyArray R PkgTerminate Terminate the library of M functions Advanced C Example This section illustrates an advanced example of how to write C code that calls a compiled M file Consider a stand alone application whose source code consists of two files multarg m which contains a function named multarg multargp c which contains a C function named main multarg m specifies two input parameters and returns two output parameters function a b multarg x y a x y pi b svd svd a The code in multargp c calls mlfMultarg and then displays the two values that mlfMultarg returns include lt stdio h gt include lt string h gt include lt math h gt include matlab h include multpkg h Include Compiler generated header file static void PrintHandler const char text printf text int main Programmer written coded to call mlfMultarg 1 define ROWS 3 define COLS 3 4 47 4 Stand Alone Applicati
224. u can accomplish this using mlib files which are automatically generated when you generate the library For more information about mlib files see mlib Files on page 5 26 Note Even if you are not producing a shared library you must generate a library wrapper file when including any Compiler generated code into a larger application Supported Executable Types This example uses several functions from the toolbox matlab timefun directory weekday date tic calendar toc to create a library wrapper The W lib libtimefun L C options produce the files shown in this table File Description libtimefun c C wrapper file libtimefun h C header file libtimefun exports C export list libtimefun mlib M file library libtimefun c The C wrapper file Libtimefun c contains the initialization libtimefunInitialize and termination libtimefunTerminate functions for the library You must call libtimefunInitialize before you call any Compiler generated code This function initializes the state of Compiler generated functions so that those functions can be called from C code not generated by the Compiler You must also call libtimefunTerminate before you unload the library The library files in this example are produced from the command mcc W lib libtimefun L C weekday date tic calendar toc C Shared Library The MATLAB Compiler allows you to build a shared library from the files created in the previous section C L
225. uilt in Library libmatlb In addition the Compiler does not honor conditional global and persistent declarations It treats global and persistent as declarations For example Limitations and Restrictions if y 3 persistent x else x 3 end Stand Alone Applications The restrictions and limitations noted in the previous section also apply to stand alone applications The functions in Table 1 2 Unsupported Functions in Stand Alone Mode are supported in MEX mode but are not supported in stand alone mode Note Stand alone applications cannot access Simulink functions Although the MATLAB Compiler can compile M files that call these functions the MATLAB C C Math library does not support them Therefore unless you write your own versions of the unsupported routines in a MEX file or as C code when you run the executable you will get a run time error Table 1 2 Unsupported Functions in Stand Alone Mode add_block callstats dbcont dbstatus dbup echo evalin get param hregister isjava add line applescript assignin close system cputime dbclear dbdown dbquit dbstack dbstep dbstop dbtype delete block delete line diary edt errorstat errortrap fields fschange functionscalled hcreate help home inferiorto inmem isglobal isruntime java javaArray Introducing the MATLAB Compiler 1 20 Table 1 2 Unsupported Functions in Stand Alone Mode Continued javaMethod lookfor mislocked ne
226. un m Incorporate the full text of the original M files into their corresponding C files as C comments mcc x h A annotation all myfun Make a generic C translation of myfun m mcc mcc t L C myfun Make a generic C translation of myfun m mcc t L Cpp myfun Make a C MEX wrapper file from myfun1 m and myfun2 m mcc W mex L C myfuni myfun2 Make a C translation and a stand alone executable from myfun1 m and myfun2 m using one mcc call mcc m myfuni myfun2 Make a C translation and a stand alone executable from myfun1 m and myfun2 m by generating each output file with a separate mcc call mcc mcc mcc mcc mcc mcc mcc st t W T sT T T L C myfunt Yields L C myfun2 Yields main L C myfuni myfun2 Yields compile exe myfuni c Yields compile exe myfun2 c Yields compile exe myfun main c Yields myfuni c myfun2 c myfuni main c myfuni o myfun2 o myfuni main o link exe myfuni o myfun2 0 myfuni main o Note On PCs filenames ending with o above would actually end with obj Compile plus1 m into an Excel add in mcc B cexcel addin addin 1 0 plus1 m 7 49 mcc 7 50 MATLAB Compiler Quick Reference This appendix summarizes the Compiler options and provides brief descriptions of how to perform common tasks Common Uses of the Compiler p A 2 Brief summary of how to use the Compiler mcc p A 4 Quick reference table of Compiler options A
227. user profile directory is windir You can determine whether or not user profiles are enabled by using the Passwords control panel Installation MATLAB Compiler To install the MATLAB Compiler on a PC follow the instructions in the Installation Guide for Windows If you have a license to install the MATLAB Compiler it will appear as one ofthe installation choices that you can select as you proceed through the installation process If the Compiler does not appear in your list of choices contact The MathWorks to obtain an updated License File license dat for multiuser network installations or an updated Personal License Password PLP for single user standard installations e Via the Web at www mathworks com On the MathWorks home page click on Support then click on the Access Login and follow the instructions Via e mail at service mathworks com ANSI C or C Compiler To install your ANSI C or C compiler follow the vendor s instructions that accompany your compiler Be sure to test the C C compiler to make sure it is installed and configured properly The following section Things to Be Aware of contains some Windows specific details regarding the installation and configuration of your C C compiler 2 17 2 installation and Configuration 2 18 Things to Be Aware of This table provides information regarding the installation and configuration of a C C compiler on your system Description Comm
228. utput Options Optimization Options Improve the performance of the generated C C code Compiler and Control Compiler behavior Environment Options mbuild mex Options Control mbuild and mex Functions By Name Sq Lr MC P 1 5 PENCON oea aa aleve Weds bo EE PO ARE DR d e T d 1 6 04 Cc 7 7 WI CA Haro soe aire Face Wess TT Ri is EO TU TITRE 7 8 ribchars alag i522 redu Shera yeh CER UL Omak RI RON wach panera LA 7 9 mbcharvector ccs 0 0 cc RR RR RR s 1 10 nou CT 7 11 mbintscalar 2 each ae RC ala ROB ol IND S Alea f alee 1 13 pnibintvectoE 1I m e a ee 4 Up Gv p ped AGE d ada 1 14 TOTS alll 42 xe eee Prae OR a EEE E RAE 1 15 mbrealscalait 2 re bars Kea boa a ke eid ee ERU Ed 7 16 mbrealvectOr 42 222 wide ees Heda wt ate dae eed da eae 7 17 MMDSCANAN ocu hace wide ea te ace Ne UE a en ata oa 7 18 IDV COLOR 2 Im doe e HE PAS o P Opt p eeayern aston tee 1 19 nisi Me PN PT 7 20 nce 1 25 external Purpose Syntax Description Pragma to call arbitrary C C functions from your M code S external The external pragma informs the Compiler that the implementation version of the function Mf will be hand written and will not be generated from the M code This pragma affects only the single function in which it appears and any M function may contain this pragma local global private or method When using this pragma the Compiler will generate an additional header file called file_external hor file_extern
229. w system rehash simget superiorto vms whos javaObject keyboard linmod macprint mactools methods mlock more munlock open system pack pfile runtime set param sim simset sldebug str2func system_dependent trmginput type what which who Fixing Callback Problems Missing Functions When the Compiler creates a stand alone application it compiles the M file you specify on the command line and in addition it compiles any other M files that your M file calls If your application includes a call to a function in a callback string or in a string passed as an argument to the feval function or an ODE solver and this is the only place in your M file this function is called the Compiler will not compile the function The Compiler does not look in these text strings for the names of functions to compile Symptom Your application runs but an interactive user interface element such as a push button is unresponsive When you close the application the graphics library issues this error message An error occurred in the callback change colormap The error message caught was Reference to unknown function change colormap from FEVAL in stand alone mode Workaround To eliminate this error create a list of all the functions that are specified only in callback strings and pass this list to the function pragma See Finding Missing Functions in an M File on page 1 21 for hints about finding functions Limitations and Restrictions
230. what the Compiler can do The MATLAB Compiler Family Pictorial view of the Compiler s output p 1 14 Why Compile M Files p 1 16 Reasons to compile M files Upgrading from Previous Versions of Compatibility issues the Compiler p 1 17 Limitations and Restrictions p 1 18 Restrictions regarding what can be compiled Introducing the MATLAB Compiler Introduction This book describes Version 3 0 of the MATLAB Compiler The MATLAB Compiler takes M files as input and generates C or C source code or P code as output The MATLAB Compiler can generate these kinds of source code C source code for building MEX files C or C source code for combining with other modules to form stand alone applications Stand alone applications do not require MATLAB at run time they can run even if MATLAB is not installed on the end user s system C code S functions for use with Simulink C shared libraries dynamically linked libraries or DLLs on Microsoft Windows and C static libraries These can be used without MATLAB on the end user s system Excel compatible plug ins e COM Component Object Model objects This chapter takes a closer look at these categories of C and C source code and explains the value of compiled code Note MATLAB Compiler 3 0 includes the MATLAB C C Math Library and the MATLAB C C Graphics Library Installing the MATLAB Compiler automatically installs the C C Math and Graphics Librari
231. when it cannot distinguish which private function to use For example given these two foo m private functions and their locations Z X private foo m Y X private foo m the Compiler searches up only one level and determines the path to the file as X private foo m Compiling Private and Method Functions Since itis ambiguous which foo m you are requesting it generates the warning Warning The specified private directory is not unique Both Z X private and Y X private are found on the path for this private directory 5 7 5 Controlling Code Generation 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 5 8 MATLAB Compiler 3 0 Date Wed Jan 23 14 51 45 2002 Arguments B macro default O all 0O fold scalar mxarrays on O fold non scalar mxarrays on O optimize integer for loops on O array indexing on Q optimize conditionals on t L C T codegen F page width 60 gasket ah ifndef MLF_V2 define MLF_V2 1 endif ifndef gasket h define X gasket h 1 ifdef X cplusplus extern
232. wo and an expression indentation of one mcc F statement indent 2 F expression indent 1 xg gasket generates the following code segment 0 1 2 3 4 5 6 7 8 12345678901234567890123456789012345678901234567890123456789012345678901234567890 void mlxGasket int nlhs mxArray plhs int nrhs mxArray prhs mxArray mprhs 1 mxArray mplhs 1 int i if nlhs gt 1 mlfError mxCreateString Run time Error File gasket Line 1 Column 1 The function gaske tV was called with more than the declared number of outputs 1 NULL if nrhs gt 1 mlfError mxCreateString Run time Error File gasket Line 1 Column 1 The function gaske tV was called with more than the declared number of inputs 1 NULL for i 0 i lt 1 i mplhs i NULL for i 0 i lt 1 amp amp i lt nrhs i mprhs i prhs i for i lt 1 i mprhs i NULL mlfEnterNewContext O 1 mprhs 0 mplhs 0 Mgasket nlhs mprhs 0 mlfRestorePreviousContext 0 1 mprhs 0 pihs 0 mplhs 0 5 39 5 Controlling Code Generation 5 40 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 fi
233. write the source code for MEX files in either Fortran or C External Interfaces API in the MATLAB documentation explains the fundamentals of this process To write MEX files you have to know how MATLAB represents its supported data types and the MATLAB external interface i e the application program interface or API If you are comfortable writing M files and have the MATLAB Compiler then you do not have to learn all the details involved in writing MEX file source code 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 Then your ANSI C compiler compiles these C source code files and the resulting object files are linked against the MATLAB C C Math and Graphics Libraries which are included with the MATLAB Compiler For more information about distributing a C application see Distributing Stand Alone Applications on page 4 27 C Stand Alone Applications The MATLAB Compiler when invoked with the p macro option translates input M files into C source code that is usable in any of the executable types except MEX The Compiler also produces the required wrapper file suitable for a stand alone application Then your C compiler com
234. y name T link lib h libmmfile mlib libmwsglm mlib B ccom lt component_name gt lt class_name gt lt version gt L cpp B cexcel lt component_name gt lt class_name gt lt version gt L cpp B chgcom lt component_name gt lt class_name gt lt version gt L cpp B csglexcel lt component_name gt lt class_name gt lt version gt L cpp B csharedlib lt shared_library_name gt L cpp T compile lib t W lib lt shared_library_name gt T link lib h libmmfile mlib 0 all G A debugline on 0 none 7 42 mcc Bundle File Name Contents macro option m main L C t T link exe h libmmfile mlib macro option p W main L cpp t T link exe h libmmfile mlib macro option S W simulink L C t T link mex libmatlbmx mlib macro option x W mex L C t T link mexlibrary libmatlbmx mlib opt bundle all O fold scalar mxarrays on O fold non scalar mxarrays on O optimize integer for loops on 0 array indexing on 0 optimize conditionals on opt bundle none O fold scalar mxarrays off O fold non scalar mxarrays off O optimize integer for loops off 0 array indexing off 0 optimize conditionals off O speculate off pcode t LP sgl m W mainhg libmwsglm mlib sglcpp p W mainhg libmwsglm mlib c C Code Only When used with a macro option generate C code but do not invoke mex or mbuild i e do not produce a MEX file or stand alone application This is equivalent to T codegen placed a

Download Pdf Manuals

image

Related Search

Related Contents

v.Logic TVRR-CL02 Bedienungsanleitung  PMDX-120 Parallel Port Accessory Module User`s Manual  取 扱 説 明 書  XL Go_16p.indd - GE Measurement & Control  OmniMount SCM125 flat panel ceiling mount  Centon 1GBS/D2-667 memory module  Manual Energia Fotovoltaica - Portal energias renovaveis  IBM Switch 15 User's Manual  THE USER'S GUIDE TO PROTIM 418  

Copyright © All rights reserved.
Failed to retrieve file