MATLAB CompilerThe Language of Technical ComputingComputationVisualizationProgrammingUser’s GuideVersion 2.1
viii Contents
4 Stand-Alone Applications4-30Licensing Problem. If you do not have a valid lice nse for the MATLAB Co mpile r,you will get an error message similar t
Coding with M-Files Only4-31Coding with M-Files OnlyOne way to create a stand-alone application is to write all the source code inone or more M-files
4 Stand-Alone Applications4-32The -m option flag causes the MATLAB Compiler to generate C source codesuitable for stand-alone applications. For exampl
Coding with M-Files Only4-33Figure 4-2: Building Two M-Files into a Stand-Alone C Applicationmrank.mmcc -t mrank.mmrank.cC CompilerObject FileC Compi
4 Stand-Alone Applications4-34For C++ code, add -L cpp to the previous commands, use a C++ compilerinstead of a C compiler, and use the MATLAB C/C++ M
Alternative Ways of Compiling M-Files4-35Alternative Ways of Compiling M-FilesThe previous section showed how to compile main.m and mrank.m separately
4 Stand-Alone Applications4-36To compile and link all four C source code files (main.c, rank.c, mrank.c,andmain_main.c) into a stand-alone application
Mixing M-Files and C or C++4-37Mixing M-Files and C or C++The examples in this section illustrate how to mix M-files and C or C++ sourcecode files:•Th
4 Stand-Alone Applications4-38The Build ProcessThe steps needed to build this stand-alone application are:1 Compile the M-code.2 Generate the library
Mixing M-Files and C or C++4-39Figure 4-3: Mixing M-Files and C Code to Form a Stand-Alone Applicationmrank.mmcc -t -W lib:Pkg -T link:exe mrank mran
1Introducing theMATLAB CompilerIntroduction ...1-2BeforeYouBegin...1-2NewFeatures...1-3CompilerLicen
4 Stand-Alone Applications4-40mrankp.cThecodeinmrankp.c calls mrank and outputs the values that mrank returns./* * MRANKP.C * "Posix" C main
Mixing M-Files and C or C++4-41 /* Print the results. */ mlfPrintMatrix(R); /* Free the matrices allocated during this computation. */
4 Stand-Alone Applications4-42mlfPrintMatrix is one of the many routines in the MATLAB Math Built-InLibrary, which is part of the MATLAB Math Library
Mixing M-Files and C or C++4-43 mxArray *a, *b, *x, *y; double x_pr[ROWS * COLS] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; double x_pi[ROWS * COLS]
4 Stand-Alone Applications4-44You can build this program into a stand-alone application by using thecommand:mcc -t -W lib:multpkg -T link:exe multarg
Mixing M-Files and C or C++4-45The mlfMultarg function returns matrices a and b. a has both real andimaginary components;b is a scalar having only a r
4 Stand-Alone Applications4-46
5ControllingCode GenerationCode Generation Overview ...5-3Compiling Private and Method Functions ...5-6The Generated Header Files ...
5 Controlling Code Generation5-2This chapter describes the code generated by the MATLAB Compiler and theoptions that you can use to control code gener
Code Generation Overview5-3Code Generation OverviewExample M-FilesTo generate the various files created by the Compiler, this chapter uses severaldiff
1 Introducing the MATLAB Compiler1-2IntroductionThis book describes version 2.1 of the MATLAB®Compiler. The MATLABCompiler tak es M-files as input and
5 Controlling Code Generation5-4foo M-Filefunction [a, b] = foo(x, y)if nargout == 0elseif nargout == 1a = x;elseif nargout == 2a = x;b = y;endfun M-F
Code Generation Overview5-5This table shows the names of the files generated when you compile a genericM-file (file.m) for the MEX and stand-alone tar
5 Controlling Code Generation5-6Compiling Private and Method FunctionsPrivate functions are functions that reside in subdirectories with the specialna
Compiling Private and Method Functions5-7This table lists the functions you can specify on the command line and theircorresponding function and filena
5 Controlling Code Generation5-8The Generated Header FilesThis section hig hlights the two header files that the Compiler can generate fo rthe Sierpin
The Generated Header Files5-9extern void mlxGasket(int nlhs, mxArray * plhs[], int nrhs,
5 Controlling Code Generation5-10void mlxGasket(int nlhs, mxArray * plhs[], int nrhs, mxArray * prhs[]);#end
Internal Interface Functions5-11Internal Interface FunctionsThis section uses the Sierpinski Gasket example (gasket.m) to s how several ofthe generate
5 Controlling Code Generation5-12 mxArray * mprhs[1]; mxArray * mplhs[1]; int i;mlfF Interface FunctionTheCompileralwaysgeneratesthemlfF inte
Internal Interface Functions5-13mlfNF Interface FunctionThe Compiler produces this interface function only when the M-function usesthe variablenargout
1-3New FeaturesMATLAB Compiler 2.1 supports much of the functionality of MATLAB 6. Thenew features of the Compiler are:•Optimizations•mlib files•Addit
5 Controlling Code Generation5-14 * outputs based on the number of non-NULL inputs it * receives. This function processes any input arguments * and pa
Internal Interface Functions5-15 * output. The void interface function specifies zero * output arguments to the implementation version of the * functi
5 Controlling Code Generation5-16would use the feval interface. The fo llowing C++ c ode is the correspondingfeval interface(mlxGasket)fromtheSierpins
Internal Interface Functions5-17F Interface FunctionThe Com p ile r always generate s the F interface function, which contains the“normal” C++ interfa
5 Controlling Code Generation5-18// interface which dynamically calculates the number of// outputs based on the number of non-NULL inputs it// receive
Internal Interface Functions5-19// version still returns an output (which, in MATLAB, would// be assigned to the "ans" variable), it dealloc
5 Controlling Code Generation5-20Supported Executable TypesWrapper functions create a link between the Compiler-generated code and asupported e xecuta
Supported Executable Types5-21MEX-FilesThe -W mex -L C options produce the MEX-file wrapper, which includes themexFunction interface that is standard
5 Controlling Code Generation5-22The Compiler processes the string arguments passed to the main() functionand sends them into the compiled M-function
Supported Executable Types5-23Simulink S-FunctionsThe -W simulink -L C options produce a Simulink S -function wrapper.Simulink S-function wrappers con
1 Introducing the MATLAB Compiler1-4mlib Filesmlib filesmake it possible toproduceashared libraryout of a toolboxand thencompile M -files that make ca
5 Controlling Code Generation5-24This example uses several functions from the toolbox\matlab\timefundirectory (weekday, date, tic, calendar, toc) to c
Supported Executable Types5-25mlib FilesShared libraries, like libraries, let you compile a common set of functions onceand then compile other M-funct
5 Controlling Code Generation5-26executable is created, it is linked against the shared library. For example onthe PC, th e executabletimer.exe is cre
Supported Executable Types5-27This example uses several functions from the toolbox\matlab\timefundirectory (weekday, date, tic, calendar, toc) to crea
5 Controlling Code Generation5-28Note Stand-alone applications require that the MATLAB C/C++ MathLibrary be purchased for each platform where the Com
Formatting Compiler-Generated Code5-29Formatting Compiler-Generated CodeThe f ormatting options allow you to control the l ook of the Compiler-generat
5 Controlling Code Generation5-3001234567812345678901234567890123456789012345678901234567890123456789012345678901234567890for (mclForStart(
Formatting Compiler-Generated Code5-31 &corners, mlfDoubleMatrix( 3, 2, _array0_, (double *)NULL)); /*
5 Controlling Code Generation5-32Default IndentationNot specifying indent formatting options uses the default of four spaces forstatements and two spa
Formatting Compiler-Generated Code5-33Modified IndentationThis example shows the same segment of code using a statement indentationof two and an expre
1-5Additional Language Supportpause and continue. These commands are now supported.eval and input. eval and input are s uppo rte d for strings that do
5 Controlling Code Generation5-34Including M-File Information in Compiler OutputTheannotationoptionsallowyoutocontrolthetypeofannotationintheCompiler-
Including M-File Information in Compiler Output5-35All AnnotationTo i nclude both comments and source code from the source M-file in thegenerated outp
5 Controlling Code Generation5-36No AnnotationTo include no source from the initial M-file in the generated output, usemcc -A annotation:none …Thiscod
Including M-File Information in Compiler Output5-37Include #line DirectivesTo include #line directives in your generated C or C++ code, usemcc -A line
5 Controlling Code Generation5-38Controlling Information in Run-Time ErrorsUse the debugline:setting option to include source filenames and linenumber
Including M-File Information in Compiler Output5-39your results areNote When using the -A debugline:on option, the lasterr function returnsa string t
5 Controlling Code Generation5-40Interfacing M-Code to C/C++ CodeThe MATLAB Compiler 2.1 supports c alling arbitrary C/C++ functions fromyour M-code.
Interfacing M-Code to C/C++ Code5-41private, or method). When using this pragma, the Compiler will generate anadditional header file calledfile_extern
5 Controlling Code Generation5-42We recommend tha t you include this header file when defining the function.This function could be implemented in this
Interfacing M-Code to C/C++ Code5-43callback that references the specified function. Without this pragma, the -hoption will not be able to locate and
1 Introducing the MATLAB Compiler1-6Running Compiler from DOS/UNIX ShellIf you run the Compiler from a DOS or UNIX shell, you are running from“outside
5 Controlling Code Generation5-44Print HandlersA print handler i s a routine that controls how your application displays theoutput generated by calls
Print Handlers5-45The applic at io n is buil t from two fil es:•mrankwin.c, which contains WinMain, WinPrint (the print handler), a nd arelated functi
5 Controlling Code Generation5-46The print handler that you write must:•Take a single argument of typeconst char * that points to the t ext to bedispl
Print Handlers5-47•The print handler routine itself that deposits the text passed to it in anoutput buffervoid WinPrint( char *text){ int cnt;
5 Controlling Code Generation5-48Main Routine Written in M-CodeIf your main routine is an M-file, you must:•Write a print handler in C.•Register the p
Print Handlers5-49•mrank.m determines the rank of the magic squares from 1 to n.function r = mrank(n)r = zeros(n, 1);for k = 1:n r(k) = rank(magic(k
5 Controlling Code Generation5-50Naming the Print Handler Initialization Routine in C. Whenyouwritetheprinthandlerinitializatio n routine in C, you m
Print Handlers5-51Initializing the Print Handler in Your Main M-File. Call the dummy print handlerinitialization routine in the first executab le line
5 Controlling Code Generation5-52
6Optimizing PerformanceOptimization Bundles ...6-3Optimizing Arrays ...6-5ScalarArrays...6-5NonscalarArray
Uses of the Compiler1-7Uses of the CompilerThe MATLAB Compiler (mcc) can translate M-files into C f iles. The r esultantC files can be used in any of
6 Optimizing Performance6-2The MATLAB Compiler can perform several different optimizations on yourM-file source code that can make the performance of
Optimization Bundles6-3Optimization BundlesAll optimizatio ns are controlled separately, and you can enable or disable anyof the optimizations. To sim
6 Optimizing Performance6-4List All OptimizationsTo list all available optimizations, use-O list
Optimizing Arrays6-5Optimizing ArraysScalar Arrays(fold_scalar_mxarrays) When this optimization is enabled, all constant,scalar-valued array operation
6 Optimizing Performance6-6If you compile this with the -O none option, you get...mlfAssign(&y,mclMtimes(mlfDoubleMatrix(2, 2, _array0_, (double *
Optimizing Loops6-7Optimizing LoopsSimple Indexing(array_indexing) T his optim ization improves the performance of simple one-and two-dimensional arra
6 Optimizing Performance6-8Note This optimization causes the variable names in the resulting Cprogram to differ from those in the M-file. Therefore,
Optimizing Loops6-9...for (; ; ) {...if (v_ == e_) {break;}++v_;}mlfAssign(&i, mlfScalar(v_));}...
6 Optimizing Performance6-10Optimizing Conditionals(optimize_conditionals) This optimization reduces the MATLAB conditionaloperators to scalar C condi
7ReferencePragmas ...7-4%#external...7-5%#function...7-6%#mex...7-7Function
1 Introducing the MATLAB Compiler1-8Figure 1-1: Developing MEX-FilesMATLAB users who do not have the MATLAB Compilermust write the sourcecode for M E
7-2This chapter provides reference information for the MATLAB Compilerpragmas, functions, and command line tools.Pragmas%#externalCall arbitrary C/C++
7-3Command Line ToolsmbuildCustomize b uilding and linking.mccInvoke MATLAB Compiler.MATLAB CompilerOptions FlagsIntroduces Compiler options.Macro Opt
Pragmas7-4PragmasPragmas are compiler-specific commands that provide special information tothe Compiler. This section contains the reference pages for
%#external7-57%#externalPurpose Pragma to call arbitrary C/C++ functions from your M-code.Syntax %#externalDescription The %#external pragma informs t
%#function7-67%#functionPurpose feval pragma.Syntax %#function <function_name-list>Description This pragma informs the MATLAB Compile r that the
%#mex7-77%#mexPurpose mex pragma.Syntax %#mexDescription This pragma informs the MATLAB Compiler to select the MEX -file over anexisting M-file.If you
Functions7-8FunctionsThis section contains the reference pages for t he C ompiler functions. Many ofthese functions are i ncl uded tomaintain backward
mbchar7-97mbcharPurpose Assert variable is a MATLAB character string.Syntax mbchar(x)Description The statementmbchar(x)causes the MATLAB Compiler to i
mbcharscalar7-107mbcharscalarPurpose Assert variable is a character scalar.Syntax mbcharscalar(x)Description The statementmbcharscalar(x)causes the MA
mbcharvector7-117mbcharvectorPurpose Assert variable is a character vector, i.e., a MATLAB string.Syntax mbcharvector(x)Description The statementmbcha
Uses of the Compiler1-9Creating Stand-Alone ApplicationsC Stand-Alone ApplicationsThe MATLAB Compiler, when invoked with the -m macro option, translat
mbint7-127mbintPurpose Assert variable is integer.Syntax mbint(n)Description The statementmbint(x)causes the MATLAB Compiler to impute that x is an in
mbint7-13mbint does not consider the value of x an integer because one of the parts (theimaginary) has a fractional component.x = 4 + 7.5i;Example Thi
mbintscalar7-147mbintscalarPurpose Assert variable is integer scalar.Syntax mbintscalar(n)Description The statementmbintscalar(x)causes the MATLAB Com
mbintvector7-157mbintvectorPurpose Assert variable is integer vector.Syntax mbintvector(n)Description The statementmbintvector(x)causes the MATLAB Com
mbreal7-167mbrealPurpose Assert variable is real.Syntax mbreal(n)Description The statementmbreal(x)causes the MATLAB Compiler to impute that x is real
mbrealscalar7-177mbrealscalarPurpose Assert variable is real scalar.Syntax mbrealscalar(n)Description The statementmbrealscalar(x)causes the MATLAB Co
mbrealvector7-187mbrealvectorPurpose Assert variable is a real vector.Syntax mbrealvector(n)Description The statementmbrealvector(x)causes the MATLAB
mbscalar7-197mbscalarPurpose Assert variable is scalar.Syntax mbscalar(n)Description The statementmbscalar(x)causes the MATLAB Compiler to impute that
mbvector7-207mbvectorPurpose Assert variable is vector.Syntax mbvector(n)Description The statementmbvector(x)causes the MATLAB Compiler to impute that
reallog7-217reallogPurpose Natural logarithm for nonnegative real inputs.Syntax Y = reallog(X)Description reallog is an elementary function that opera
How to Contact The MathWorks:508-647-7000 Phone508-647-7001 FaxThe MathWorks, Inc. Mail3AppleHillDriveNatick, MA 01760-2098http://www.mathworks.com We
1 Introducing the MATLAB Compiler1-10Figure 1-2: Developing a Typical Stand-Alone C ApplicationM-File function to find therank of a magic squaremcc -
realpow7-227realpowPurpose Array power function for real-only output.Syntax Z = realpow(X,Y)Description realpow returns X raised to the Y power. realp
realsqrt7-237realsqrtPurpose Square root for nonnegative real inputs.Syntax Y = realsqrt(X)Description realsqrt(X) returns the square root of the elem
Command Line Tools7-24Command Line ToolsThis section containsthe reference pages for the Compiler comma nd line tools,namely,mbuild and mcc. This sect
mbuild7-257mbuildPurpose Compile and link source files that call functions in the MATLAB C/C++ MathLibrary or MATLAB C/C++ Graphics Library into a sta
mbuild7-26-f <<optionsfile>>Specify location and name of options fileto use. Overrides thembuild defaultoptions file search mechanism.-gCr
mbuild7-27-lang <language>Specify compiler language. <language>can be c or cpp. By default, mbuilddetermines which compiler (C or C++) tou
mbuild7-28-setupInteractively specify the compiler optionsfile to use as default for futureinvocations ofmbuild by placing it in<UserProfile>\Ap
mbuild7-29Note Some of these op tions (-f, -g,and-v) are available on the mcccommand line and are passed along to mbuild. Others can be passed alongu
mcc7-307mccPurpose Invoke MATLAB Compiler.Syntax mcc [-options] mfile1 [mfile2 ... mfileN][C/C++file1 ... C/C++fileN]Description mcc is the MATLAB com
mcc7-31compilation, you can use one simple optio n, i.e., macro, that allows you toquickly accomplish basic compilation tasks. If you want to take adv
Uses of the Compiler1-11See “Stand-Alone Applications” for complete details regarding stand-aloneapplications.Figure 1-2 illustrates the process of de
mcc7-32Understanding a Macro Option. Th e -m option t ells the Compiler to produce astand-alone C application. The-m macro is equiv alent t o the seri
mcc7-33mcc searchesfor the mccstartup fileinthesetwodirectoriesintheorder shownabove. If it finds anmccstartup file, itreads it and processes the opti
mcc7-34Conflicting Options on Command LineIf you use conflicting options, the Compiler resolves them from left to right,with the rightmost option taki
mcc7-35would be equivalent tomcc -m -I /home/user/dir1 -I /home/user/dir2 myfile.mThe Compiler finds the myfile.m in dir1 and compiles it instead of t
mcc7-36MATLAB Compiler Option FlagsThe MATLAB Compiler option flags perform various functions that affect thegenerated code and how the Compiler behav
mcc7-37For example, to translate an M-file named mymfile.m into C and to create astand-alone executable that can be run without MATLAB, usemcc -m mymf
mcc7-38The -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
mcc7-39To control the #line preprocessor directives that are includedin the generatedC/C++ source, usemcc -A line:setting …The table shows the availab
mcc7-40To include none of your M-code and no #line preprocessor directives, usemcc -A annotation:none -A line:off …Toincludethestandard#line preproces
mcc7-41-l (Line Numbers) . Generate C/C++ code that prints filename and line numberson run-time errors. This option flag is useful for debugging, but
1 Introducing the MATLAB Compiler1-12The MATLAB Compiler FamilyThis figure i llustrat es the various ways you can use t he MAT LAB Compiler.The shaded
mcc7-42-W <type> (Function Wrapper). Control the generation of function wrappers for acollection of Compiler-generatedM-files.Youprovide a list
mcc7-43Compiler and Environment Options-B <filename> (Bundle of Compiler Settings). Replace -B <filename> on the mcccommand line with the
mcc7-44would set up the search path so that directory1 is searched first for M-files,followed bydirectory2. This option is important for stand-alone c
mcc7-45The -v option passes the -v option to mex or mbuild and displays informationaboutmex or mbuild.-w (Warning). Displaywarningmessages.Thistablesh
mcc7-46mbuild/mex Options-f <filename> (Specifying Options File). Use the sp ecif ie d options file when callingmex or mbuild. T his option a ll
mcc7-47Make a C translation and a Simulink S-function for myfun.m (usingdynamically sized inputs and outputs).mcc -S myfunMake a C translation and a S
mcc7-48Make a C translation and a stand-alone executable from myfun1.m andmyfun2.m (by generating each output file with a separate mcc call).mcc -t -L
AMATLAB CompilerQuick ReferenceCommon Uses of the Compiler ...A-2mcc ...A-4
A MATLAB Compiler Quick ReferenceA-2Common Uses of the CompilerThis section summarizes how t o use the MATLAB Comp iler to generate someof its more st
A-3Create a C++ Library. T o create a C+ + library, usemcc -p -W lib:libfoo -T compile:lib foo.mCreate a C Shared Library. To create a C shared librar
The MATLAB Compiler Family1-13The Compiler takes your M-file(s) and can generate C or C++ code. It can alsogenerate one of four wrapper files dependin
A MATLAB Compiler Quick ReferenceA-4mccBold entries in the Comment/Options column indicate default values.Option Description Comment/OptionsA annotati
mccA-5hCompiles helper functionsI directoryAdds new directory to pathlGenerates code that reportsfile and line numbers onrun-time errorsEquivalent to:
A MATLAB Compiler Quick ReferenceA-6T targetSpecifies output stagetarget = codegencompile:binlink:binwhere bin = mexexelibu numberSpecifies number of
mccA-7z pathSpecifies path for libraryand include files?Displays help messageOption Description Comment/Options
A MATLAB Compiler Quick ReferenceA-8
BError and WarningMessagesCompile-Time Errors ...B-3Warning M essages ...B-12Run-Time Errors ...B-19
B Error and Warning MessagesB-2This appendix lists and describes error messages and warnings generated bythe MATLAB Compiler. Compile-time messages ar
Compile-Time ErrorsB-3Compile-Time ErrorsError: An error occurred while shelling out to mex/mbuild (error code = errorno). Unable to build executable
B Error and Warning MessagesB-4Error: File: filename Line: # Column: # () indexing must appear last in an index expression.If you use ordinary array i
Compile-Time ErrorsB-5Error: File: filename Line: # Column: # An array for multiple LHS assignment cannot contain token. If t he left-hand side of a s
1 Introducing the MATLAB Compiler1-14Why Compile M-Files?There a re three main reasons to compile M-files:•To create stand-alone applications or C sha
B Error and Warning MessagesB-6Error: File: filename Line: # Column: # Missing variable or function. An illeg al name wasused for a variable or functi
Compile-Time ErrorsB-7Error: File: filename Line: # Column: # The single colon operator (:) can only be used within an array index expression.You can
B Error and Warning MessagesB-8Error: Improper usage of option -optionname. Type "mcc -?" for usage information. Youhave incorrectly used a
Compile-Time ErrorsB-9Error: The environment variable MATLAB must be set to the MATLAB root directory. OnUNIX, theMATLAB and LM_LICENSE_FILE variables
B Error and Warning MessagesB-10Error: The -option option cannot be combined with other options. The -V2.0 optionmust appear separate from other optio
Compile-Time ErrorsB-11Error: Unknown typesetting option: optionname. The valid typesetting optionsavailable with-F are expression-indent:n, list, pag
B Error and Warning MessagesB-12Warning MessagesThis section lists the warning messag es that the MAT LAB Compiler 2.1 cangenerate. Using the-w option
Warning MessagesB-13Warning: File: filename Line: # Column: # The call to function "functionname" on this line could not be bound to a funct
B Error and Warning MessagesB-14Warning: File: filename Line: # Column: # The call to function "functionname" on this line passed quantity1
Warning MessagesB-15Warning: File: filename Line: # Column: # The load statement cannot be translated unless it specifically lists the names of variab
Why Compile M-Files?1-15Cases When Performance Does Not Improve. Compilation is not like ly to speed upM-file functions that:•Are heavily vectorized•S
B Error and Warning MessagesB-16Warning: File: filename Line: # Column: # The second output argument from the "functionname" function is onl
Warning MessagesB-17Warning: M-file "filename" was specified on the command line with full path of "pathname", but was found on th
B Error and Warning MessagesB-18Warning: The name of a shared library should begin with the letters "lib". "libraryname" doesn’t.(
Run-Time ErrorsB-19Run-Time ErrorsNote The error messages described in this section are generated by theCompiler into t he code exactly as they are w
B Error and Warning MessagesB-20Run-time Error: File: filename Line: # Column: # The function "functionname" was called with more than the d
I-1IndexSymbols#line directives 5-36%#external 7-5%#function 7-6%#mex 7-7%#mex pragma 7-7.cshrc 4-12.DEF file 4-22A-A option flag 7-38add-inMATLAB for
IndexI-2setting indentation 5-29setting width 5-29command duality 5-21compiled code vs. interpreted code 1-14compilerC++ requirements 4-7changing defa
IndexI-3filelicense.dat 2-7, 2-18mccpath 7-33mlib 5-23, 5-25wrapper 1-7for. See loops.formatting code 5-29-F option flag 7-40listing all options 5-29s
IndexI-4interface f unction 5-11interfacing M-code to C/C++ code 5-40internal error B-2invokingMEX-files 3-5M-files 3-4L-L option flag 7-41-l option f
IndexI-5generating source files 5-20getting started 3-1good M-files to compile 1-15installing o nPC 2-14UNIX 2-5, 2- 7installing on Microsoft Windows
1 Introducing the MATLAB Compiler1-16Upgrading from Previous VersionsMATLAB Compiler 2.0The MATLAB Compiler 2.1 does not support the -V1.2 option that
IndexI-6suppressing invocation of 7-43verifyingon Microsoft Windows 2-23on UNIX 2-11MEX wrapper 1-7, 5-21MEX-filebus error 2-26comparison to stand-alo
IndexI-7measuring performance 3-4nonscalar array s 6-5-O <optimization option> 6-3-O all 6-3-O list 6-4-O none 6-3optimization bundles 6-3scalar
IndexI-8private functionambiguous names 5-7compiling 5-6problem with license 2-18Rrank 4-35reallog 7- 21real-only functionsreallog 7- 21realpow 7- 22r
IndexI-9stand-alone C++ applicationssystem requirements 4-4stand-alone Compilersetting path 7-33stand-alone graphics applicationsgenerating C applicat
IndexI-10wrapper file 1-7MEX 1-7target types 1-13wrapper function 5-20X-x option flag 7-37Y-Y option flag 7-45-y option flag 3-9, 7-42Z-z option flag
Limitations and Restrictions1-17Limitations and RestrictionsMATLAB CodeThis version of the MATLAB Compiler supports almost all of the functionalityof
1 Introducing the MATLAB Compiler1-18Stand-Alone ApplicationsThe restrictions and limitations noted in the previous section also apply tostand-alone a
Limitations and Restrictions1-19rehash runtime set_param simsimget simset sldebug str2funcsuperiorto system_dependent trmginput typevms what which who
iContents1Introducing the MATLAB CompilerIntroduction ... 1-2BeforeYouBegin...
1 Introducing the MATLAB Compiler1-20
2Installation andConfigurationSystem Configuration f or MEX-Files ...2-3UNIX Workstation ...2-5SystemRequirements...
2 Installation and Configuration2-2This chapter explains:•The system requirements you need to use the MATLAB Compiler•How to install the MATLAB Compil
System Configuration for MEX-Files2-3System Configuration for MEX-FilesThis section outlines the steps necessary to configure your system to createMEX
2 Installation and Configuration2-4Figure 2-1: MATLAB Compiler Installation Sequence for Creating MEX-FilesStartIs ANSI C or C++compiler installedFol
UNIX Workstation2-5UNIX WorkstationThis section examines the system requirements, installation procedures, andconfiguration p rocedures for the MATLAB
2 Installation and Configuration2-6Note Although the MATLAB Compiler supports the creation of stand-aloneC++ applications, it does not support the cr
UNIX Workstation2-7shows the preconfig ured options files that are included with MATLAB forUNIX.Informati on on the options files is provide d for tho
2 Installation and Configuration2-8ANSI C or C++ CompilerTo install your ANSI C or C++ compiler, follow the vendor’s instructions thataccompany your C
UNIX Workstation2-9If you do not need to change C or C++ compilers, or you do not need to modifyyour compiler options files, you can skip ahead in thi
ii ContentsUNIX Workstation ... 2-5SystemRequirements ... 2-5Installation . ...
2 Installation and Configuration2-10Note The setup option creates a user-specific, matlab directory in yourindividual home director y and copies the
UNIX Workstation2-11OnUNIX,MEX-fi lesarecreatedwithplatform-specifi cextensions,asshowninthis table .The<matlab>/extern/examples/mex directory c
2 Installation and Configuration2-12MATLAB Compiler VerificationVerifying from MATLABOnceyouhaveverifiedthatyoucangenerateMEX-filesonyoursystem,youare
UNIX Workstation2-13Next, verify that invhilb is now a MEX-file by listing the invhilb files.ls invhilb.*You wil l see a lis t s imila r to this.invhi
2 Installation and Configuration2-14Microsoft Windows on PCsThis section examines the system requirements, installation procedures, andconfiguration p
Microsoft Windows on PCs2-15Note Although the MATLAB Compiler supports the creation of stand-alo neC++ applications, it does not support the creati o
2 Installation and Configuration2-16•The MATLAB Compiler 2.1 sometimes will generate goto statements forcomplicatedif conditions. The Borland C++ Comp
Microsoft Windows on PCs2-17Compiler Options FilesThe MathWorks provides options files for every supported C or C++ compiler.These files contain the n
2 Installation and Configuration2-18created during the -setup process, in a subdirectory of your user profiledirectory,named Application Data\MathWork
Microsoft Windows on PCs2-19Things to Be Aware ofThis table provides information regarding the installation and configuration ofaC/C++compileronyoursy
iii4Stand-Alone ApplicationsDifferences B etween MEX-Filesand Stand-Alone Applications ...4-3Stand-AloneCApplications...
2 Installation and Configuration2-20mex VerificationChoosing a CompilerSystems with Exactly One C/C++ Compiler. If you have properly installed theMATL
Microsoft Windows on PCs2-21[1] : Borland compiler in T:\Borland\BC.500[2] : WATCOM compiler in T:\watcom\c.106[0] : NonePlease select a compiler. Thi
2 Installation and Configuration2-22[0] NoneCompiler: 11Your machine has a Microsoft Visual C/C++ compiler located at D:\Applications\Microsoft Visual
Microsoft Windows on PCs2-23copy of the options file in your user profile directory to correspond to yourspecific needs and sa ve the mo difie d file.
2 Installation and Configuration2-24information about the add-in, see “Using an IDE” in Chapter 4, “Stand-AloneApplications.”MATLAB Compiler Verificat
Microsoft Windows on PCs2-25Copyinvhilb.mfromthe<matlab>\toolbox\matlab\elmat directory toalocaldirectory and then type the following at the DOS
2 Installation and Configuration2-26TroubleshootingThis section identifies some of the more common problems that can occurwheninstalling and configuri
Troubleshooting2-27works from the UNIX shell prompt b ut does not work from the MATLABprompt, you may have a problem with your.cshrc file. When MATLAB
2 Installation and Configuration2-28Troubleshooting the CompilerOne problem that might occur when you try to use the Compiler involveslicensing.Licens
3Getting Startedwith MEX-FilesA Simple Example - The Sierpinski Gasket ...3-3InvokingtheM-File ...3-4Compiling the M -File into a MEX
iv ContentsMixing M-Files and C or C++ ... 4-37SimpleExample ... 4-37AdvancedCExample...
3 Getting Started with MEX-Files3-2This chapter gets you started compiling M-files with the MATLAB Compiler.By the end of this chapter, you should kno
A Simple Example - The Sierpinski Gasket3-3A Simple Example - The Sierpinski GasketConsider an M-file function called gasket.m.function theImage = gas
3 Getting Started with MEX-Files3-4The curve ca n be graphed in many ways. Sierpinski's method is:•Start with a triangle and from it remove a tri
A Simple Example - The Sierpinski Gasket3-5Note The timi n gs listed in this bo ok were recorded on a Pen tium Pro 200MHz PC running Microsoft Window
3 Getting Started with MEX-Files3-6tic; x = gasket(50000); tocMATLAB runs the MEX-file version (gasket.mex) rather than the M-fileversion (gasket.m).
Compiler Options and Macros3-7Compiler Options and MacrosThe MATLAB Compiler uses a family of options, also called option flags, tocontrol the functio
3 Getting Started with MEX-Files3-8Generating Simulink S-FunctionsYou can use the MATLAB Compile r to generate Simulink C MEX S-functions.This allow s
Generating Simulink S-Functions3-9The result is an S-function described in the follow ing files.mfilename.cmfilename.hmfilename_simulink.cmfilename.ex
3 Getting Started with MEX-Files3-10Data TypeThe input and output vectors for the Simulink S-function must bedouble-precision vectors or scalars. You
Converting Script M-Files to Function M-Files3-11Converting Script M-Files to Function M-FilesMATLAB provides two ways to package sequences of MATLAB
vIncluding M-File Information in Compiler Output ... 5-34ControllingCommentsinOutputCode ... 5-34Controlling#lineDirectivesinOutputC
3 Getting Started with MEX-Files3-12in the MATLAB workspace. If it is important to have m accessible from theMATLAB workspace, you can change the begi
4 Stand-AloneApplicationsDifferences Between MEX-Filesand Stand-Alone Applications ...4-3Building Stand-Alone C/C++ Applications ...4-5Buil
4 Stand-Alone Applications4-2This chapter explains how to use the MATLAB Compiler to code and buildstand-alone applications. The first part of the cha
Differences Between MEX-Files and Stand-Alone Applications4-3Differences Between MEX-Files and Stand-Alone ApplicationsMEX-files and stand-alone appli
4 Stand-Alone Applications4-4The MATLAB Compiler translates input M-files into C source code suitable foryour own stand-alone applications. After comp
Building Stand-Alone C/C++ Applications4-5Building Stand-Alone C/C++ ApplicationsThis section explains how to build stand-alone C and C++ applications
4 Stand-Alone Applications4-6This figure shows the sequence on both platforms. The sections following theflowchart provide more specific details for t
Building Stand-Alone C/C++ Applications4-7Getting StartedIntroducing mbuildThe MathWorks utility, mbuild, lets you customize the configuration and bui
4 Stand-Alone Applications4-8Building Stand-Alone Applications on UNIXThis section explains how to compile and link C or C++ source code into astand-a
Building Stand-Alone Applications on UNIX4-9Locating Options Filesmbuild locates your options file by searching the following:•T he current directory•
vi Contents7ReferencePragmas ... 7-4%#external ... 7-5%#function ...
4 Stand-Alone Applications4-10The setup option creates a user-specific options file for your ANSI C or C++compiler. Executingmbuild -setup presents a
Building Stand-Alone Applications on UNIX4-11Modifying the Options File. Another use of the setup o ption is if you want tochange your options file se
4 Stand-Alone Applications4-12specified options file for the current execution of mbuild only; it does not resetthe default compiler.Verifying mbuildT
Building Stand-Alone Applications on UNIX4-13Note On all UNIX platforms, the Compi ler libra ry is shipped as a sharedobject (.so) file or shared lib
4 Stand-Alone Applications4-14typically by typing its name at the UNIX prompt. The application should runand display the messageHello, WorldWhen you e
Building Stand-Alone Applications on UNIX4-15Note If you distribute an app lication created with t he m ath li braries onDigital UNIX, your users mus
4 Stand-Alone Applications4-16Building Stand-Alone Applications on PCsThis section explains how to compile and link the C/C++ code generated fromthe M
Building Stand-Alone Applications on PCs4-17Note Yo u c an o verrid e the language choice that is determined f rom theextension by using the-lang opt
4 Stand-Alone Applications4-18This simple method works for the majority of users. Assuming filename.ccontains a main function, this e xample uses your
Building Stand-Alone Applications on PCs4-19Changing CompilersChanging the Default Compiler. To change your default C or C++ compiler, youselect a dif
viiBError and Warning MessagesCompile-Time Errors ...B-3Warning Messages ...B-12Run-Tim
4 Stand-Alone Applications4-20Linking against the C/C++ Graphics LibraryAre these correct?([y]/n): yThe default options file:"C:\WINNT\Profiles\u
Building Stand-Alone Applications on PCs4-21option into an integrated development environment (IDE) or makefile that youneedtomaintainoutsideofMATLAB.
4 Stand-Alone Applications4-222 In the C options file, within just those copied lines from step 1, replace alloccurrences of:-COMPFLAGS with CPPCOMPFL
Building Stand-Alone Applications on PCs4-23stand-alone applications are WIN32 Dynamic Link Libraries. Before runninga stand-alone application, you mu
4 Stand-Alone Applications4-24About the mbuild ScriptThe mbuild script supports various options that allow you to customize thebuilding and linking of
Building Stand-Alone Applications on PCs4-253 For either mex or stand-alone support, you should also run the followingcommands at the MATLAB prompt.cd
4 Stand-Alone Applications4-26Distributing Stand-Alone Windows ApplicationsTo distribute a stand-alone applica tio n, you must create a package contai
Building Shared Libraries4-27Building Shared LibrariesYou can use mbuild to build C shared libraries on both UNIX and the PC. Allof thembuild options
4 Stand-Alone Applications4-28TroubleshootingTroubleshooting mbuildThis section identifies some of the more common problems that might occurwhen confi
Troubleshooting4-29launches a new C shell to perform compilations, it executes the .cshrc script.If this script causes unexpected changes to thePATH e
Komentarze do niniejszej Instrukcji