| Contents | Index |
When you use Simulink software to create and execute a model, and Simulink Coder software to generate code, you may need to consider up to three platforms, often called hardware targets:
MATLAB Host — The platform that runs MathWorks software during application development
Embedded Target — The platform on which an application will be deployed when it is put into production
Emulation Target — The platform on which an application under development is tested before deployment
The same platform might serve in two or possibly all three capacities, but they remain conceptually distinct. Often the MATLAB host and the emulation target are the same. The embedded target is usually different from, and less powerful than, the MATLAB host or the emulation target; often it can do little more than run a downloaded executable file.
When you use Simulink software to execute a model for which you will later generate code, or use Simulink Coder software to generate code for deployment on an embedded target, you must provide information about the embedded target hardware and the compiler that you will use with it. The Simulink software uses this information to produce bit-true agreement for the results of integer and fixed-point operations performed in simulation and in code generated for the embedded target. The Simulink Coder code generator uses the information to create code that executes with maximum efficiency.
When you generate code for testing on an emulation target, you must additionally provide information about the emulation target hardware and the compiler that you will use with it. The code generator uses this information to create code that provides bit-true agreement for the results of integer and fixed-point operations performed in simulation, in code generated for the embedded target, and in code generated for the emulation target. The agreement is possible even though the embedded target and emulation target may use very different hardware, and the compilers for the two targets may use different defaults where the C standard does not completely define behavior.
The following table lists supported system target files and their associated code formats. The table also gives references to relevant manuals or chapters in this book. All of these targets are built using the make_rtw make command.
Note You can select any target of interest using the System Target File Browser. This allows you to experiment with configuration options and save your model with different configurations. However, you cannot build or generate code for non-GRT targets unless you have the required license on your system (Embedded Coder license for ERT, Real-Time Windows Target license for RTWIN, and so on). |
Each system target file invokes one or more template makefiles. The template makefile that is invoked activates a particular compiler (for example, Lcc, gcc, or Watcom compilers). This is specified for you by MEXOPTS, which is determined when you run mex -setup to select a compiler for mex. One exception is the Microsoft Visual C++® project target, which has separate System Target File Browser entries.
Targets Available from the System Target File Browser
Target/Code Format | System Target File | Template Makefile and Comments | Reference |
|---|---|---|---|
Embedded Coder (for PC or UNIX[a] platforms) | ert.tlc | ert_default_tmf Use mex -setup to configure for Lcc, Watcom, vc, gcc, and other compilers | |
Embedded Coder for Visual C++[b] Solution File | ert.tlc | RTW.MSVCBuild Creates and builds Visual C++ Solution (.sln) file | |
Embedded Coder for AUTOSAR | autosar.tlc | ert_default_tmf | |
Generic Real-Time for PC or UNIX platforms | grt.tlc | grt_default_tmf Use mex -setup to configure for Lcc, Watcom, vc, gcc, and other compilers | |
Generic Real-Time for Visual C++ Solution File | grt.tlc | RTW.MSVCBuild Creates and builds Visual C++ Solution (.sln) file | |
Generic Real-Time (dynamic) for PC or UNIX platforms | grt_malloc.tlc | grt_malloc_default_ Use mex -setup to configure for Lcc, Watcom, vc, gcc, and other compilers Does not support SimStruct. | |
Generic Real-Time (dynamic) for Visual C++ Solution File | grt_malloc.tlc | RTW.MSVCBuild Creates and builds Visual C++ Solution (.sln) file | |
Rapid Simulation Target (default for PC or UNIX platforms) | rsim.tlc | rsim_default_tmf Use mex -setup to configure | |
Rapid Simulation Target for LCC compiler | rsim.tlc | ||
Rapid Simulation Target for UNIX platforms | rsim.tlc | ||
Rapid Simulation Target for Visual C++ compiler | rsim.tlc | ||
Rapid Simulation Target for Watcom compiler | rsim.tlc | ||
S-Function Target for PC or UNIX platforms | rtwsfcn.tlc | Use mex -setup to configure | |
S-Function Target for LCC | rtwsfcn.tlc | ||
S-Function Target for UNIX platforms | rtwsfcn.tlc | ||
S-Function Target for Visual C++ compiler | rtwsfcn.tlc | ||
S-Function Target for Watcom | rtwsfcn.tlc | ||
Tornado (VxWorks) Real-Time Target | tornado.tlc | ||
ASAM-ASAP2 Data Definition Target | asap2.tlc | ||
Real-Time Windows Target for Open Watcom | rtwin.tlc | ||
xPC Target for Visual C++ or Watcom C/C++ compilers | xpctarget.tlc | xpc_default_tmf | |
IDE Link capability | idelink_grt.tlc | N/A | Desktop IDEs and Desktop Targets, Embedded IDEs and Embedded Targets in the Embedded Coder documentation |
[a] UNIX is a registered trademark of The Open Group in the United States and other countries. [b] Visual C++ is a registered trademark of Microsoft Corporation. | |||
When you try to build models with a nonzero start time, if the selected target does not support a nonzero start time, the Simulink Coder software does not generate code and displays an error message. The Rapid Simulation (RSim) target supports a nonzero start time when the Configuration Parameters > RSim Target > Solver selection parameter is set to Use Simulink solver module. All other targets do not support a nonzero start time.
A target (such as the GRT target) is an environment for generating and building code intended for execution on a certain hardware or operating system platform. A target is defined at the top level by a system target file, which in turn invokes other target-specific files.
A code format (such as embedded or real-time) is one property of a target. The code format controls decisions made at several points in the code generation process. These include whether and how certain data structures are generated (for example, SimStruct or rtModel), whether or not static or dynamic memory allocation code is generated, and the calling interface used for generated model functions. In general, the Embedded-C code format is more efficient than the RealTime code format. Embedded-C code format provides more compact data structures, a simpler calling interface, and static memory allocation. These characteristics make the Embedded-C code format the preferred choice for production code generation.
In prior releases, only the ERT target and targets derived from the ERT target used the Embedded-C code format. Non-ERT targets used other code formats (for example, RealTime or RealTimeMalloc).
In Release 14, the GRT target uses the Embedded-C code format for back end code generation. This includes generation of both algorithmic model code and supervisory timing and task scheduling code. The GRT target (and derived targets) generates a RealTime code format wrapper around the Embedded-C code. This wrapper provides a calling interface that is backward compatible with existing GRT-based custom targets. The wrapper calls are compatible with the main program module of the GRT target (grt_main.c or grt_main.cpp). This use of wrapper calls incurs some calling overhead; the pure Embedded-C calling interface generated by the ERT target is more highly optimized.
For a description of the calling interface generated by the ERT target, see Model Architecture and Design in the Embedded Coder documentation.
Code format unification simplifies the conversion of GRT-based custom targets to ERT-based targets. See Making Pre-R2012a Custom GRT-Based Targets ERT-Compatible for a discussion of target conversion issues.
Your choice of code format is the most important code generation option. The code format specifies the overall framework of the generated code and determines its style.
When you choose a target, you implicitly choose a code format. Typically, the system target file will specify the code format by assigning the TLC variable CodeFormat. The following example is from ert.tlc.
%assign CodeFormat = "Embedded-C"
If the system target file does not assign CodeFormat, the default is RealTime (as in grt.tlc).
If you are developing a custom target, you must consider which code format is best for your application and assign CodeFormat accordingly.
Choose the RealTime or RealTime malloc code format for rapid prototyping. If your application does not have significant restrictions in code size, memory usage, or stack usage, you might want to continue using the generic real-time (GRT) target throughout development.
For production deployment, and when your application demands that you limit source code size, memory usage, or maintain a simple call structure, you should use the Embedded-C code format. Consider using the Embedded Coder product, if you need added flexibility to configure and optimize code.
Finally, you should choose the Model Reference or the S-function formats if you are not concerned about RAM and ROM usage and want to
Use a model as a component, for scalability
Create a proprietary S-function MEX-file object
Interface the generated code using the S-function C API
Speed up your simulation
The following table summarizes how different targets support applications:
Application | Targets |
|---|---|
Fixed- or variable-step acceleration | RSIM, S-Function, Model Reference |
Fixed-step real-time deployment | GRT, GRT-Malloc, ERT, xPC Target, Wind River Systems Tornado, Real-Time Windows Target, Texas Instruments™ DSP, ... |
The following table summarizes the various options available for each Simulink Coder code format/target, with the exceptions noted.
Features Supported by Simulink Coder Targets and Code Formats
| Feature | GRT | Real- time malloc | ERT | ERT Shared Library | Wind River Systems VxWorks /Tornado | S- Func | RSIM | RT Win | xPC | Other Supported Targets1 |
|---|---|---|---|---|---|---|---|---|---|---|
Static memory allocation | X |
| X |
| X |
| X | X | X | |
Dynamic memory allocation |
| X |
|
| X | X | X |
| X |
|
Continuous time | X | X | X |
| X | X | X | X | X |
|
C/C++ MEX S-functions | X | X | X |
| X | X | X | X | X |
|
S-function (inlined) | X | X | X |
| X | X | X | X | X | X |
Minimize RAM/ROM usage |
|
| X |
| X2 |
|
|
| X2 | X |
Supports external mode | X | X | X |
| X |
| X | X | X |
|
Rapid prototyping | X | X |
|
| X |
|
| X | X | X |
Production code |
|
| X |
| X2 |
|
|
| X2 | X3 |
Batch parameter tuning and Monte Carlo methods |
|
|
| X |
|
| X |
|
|
|
System-level Simulator |
|
|
| X |
|
|
|
|
|
|
Executes in hard real time | X4 | X4 | X4 |
| X |
|
| X | X | X5 |
Non-real-time executable included | X | X | X |
|
|
| X |
|
|
|
Multiple instances of model |
| X6 | X6, 7 |
|
| X6 |
|
| X2, 6, 7 | X2, 6, 7 |
Supports variable-step solvers |
|
|
|
|
| X | X |
|
|
|
Supports SIL/PIL |
|
| X |
|
|
|
|
|
| X |
1The Embedded Targets capabilities in Simulink Coder support other targets.
2Does not apply to GRT based targets. Applies only to an ERT based target.
4The default GRT, GRT malloc, and ERT rt_main files emulate execution of hard real time, and when explicitly connected to a real-time clock execute in hard real time.
6You can generate code for multiple instances of a Stateflow chart or subsystem containing a chart, except when the chart contains exported graphical functions or the Stateflow model contains machine parented events.
7You must enable Generate reusable code in the Configuration Parameters Code Generation – Interface pane.
About Real-Time Code Format. The real-time code format (corresponding to the generic real-time target) is useful for rapid prototyping applications. If you want to generate real-time code while iterating model parameters rapidly, you should begin the design process with the generic real-time target. The real-time code format supports:
Continuous time
Continuous states
C/C++ MEX S-functions (inlined and noninlined)
For more information on inlining S-functions, see ???, and the Target Language Compiler documentation.
The real-time code format declares memory statically, that is, at compile time.
Unsupported Blocks. The real-time format does not support the following built-in user-defined blocks:
Interpreted MATLAB Function block (note that Fcn blocks are supported)
S-Function block — MATLAB language S-functions, Fortran S-functions, or C/C++ MEX S-functions that call into the MATLAB environment (Fcn block calls are supported)
grt.tlc - Generic Real-Time Target
rsim.tlc - Rapid Simulation Target
tornado.tlc - Tornado (VxWorks) Real-Time Target
grt
grt_lcc.tmf — Lcc compiler
grt_unix.tmf — The Open Group UNIX host
grt_vc.tmf — Microsoft Visual C++
grt_watc.tmf — Watcom C
rsim
rsim_lcc.tmf — Lcc compiler
rsim_unix.tmf — UNIX host
rsim_vc.tmf — Visual C++
rsim_watc.tmf — Watcom C
tornado.tmf
win_watc.tmf
About Real-Time malloc Code Format. The real-time malloc code format (corresponding to the generic real-time malloc target) is very similar to the real-time code format. The differences are
Real-time malloc declares memory dynamically.
For MathWorks blocks, malloc calls are limited to the model initialization code. Generated code is designed to be free from memory leaks, provided that the model termination function is called.
Real-time malloc allows you to deploy multiple instances of the same model with each instance maintaining its own unique data.
Real-time malloc allows you to combine multiple models together in one executable. For example, to integrate two models into one larger executable, real-time malloc maintains a unique instance of each of the two models. If you do not use the real-time malloc format, the Simulink Coder code generator will not necessarily create uniquely named data structures for each model, potentially resulting in name clashes.
grt_malloc_main.c (or .cpp), the main routine for the generic real-time malloc (grt_malloc) target, supports one model by default. See Combined Models for information on modifying grt_malloc_main.c (or .cpp) to support multiple models. grt_malloc_main.c and grt_malloc_main.cpp are located in the folder matlabroot/rtw/c/grt_malloc.
Unsupported Blocks. The real-time malloc format does not support the following built-in blocks, as shown:
Functions & Tables
Interpreted MATLAB Function block (note that Fcn blocks are supported)
S-Function block — MATLAB language S-functions, Fortran S-functions, or C/C++ MEX S-functions that call into the MATLAB environment (Fcn block calls are supported)
grt_malloc.tlc - Generic Real-Time Target with dynamic memory allocation
tornado.tlc - Tornado (VxWorks) Real-Time Target
grt_malloc
grt_malloc_lcc.tmf — Lcc compiler
grt_malloc_unix.tmf — The Open Group UNIX host
grt_malloc_vc.tmf — Microsoft Visual C++
grt_malloc_watc.tmf — Watcom C
tornado.tmf
The S-function code format (corresponding to the S-function target) generates code that conforms to the Simulink MEX S-function API. Using the S-function target, you can build an S-function component and use it as an S-Function block in another model.
The S-function code format is also used by the accelerated simulation target to create the Accelerator MEX-file.
In general, you should not use the S-function code format in a system target file. However, you might need to do special handling in your inlined TLC files to account for this format. You can check the TLC variable CodeFormat to see if the current target is a MEX-file. If CodeFormat = "S-Function" and the TLC variable Accelerator is set to 1, the target is an accelerated simulation MEX-file.
See Generated S-Function Block, for more information.
About Embedded Code Format. The Embedded-C code format corresponds to the Embedded Coder target (ERT), and targets derived from ERT. This code format includes a number of memory-saving and performance optimizations. See the Embedded Coder documentation for details.
Using the Real-Time Model Data Structure. The Embedded-C format uses the real-time model (RT_MODEL) data structure. This structure is also referred to as the rtModel data structure. You can access rtModel data by using a set of macros analogous to the ssSetxxx and ssGetxxx macros that S-functions use to access SimStruct data, including noninlined S-functions compiled by the Simulink Coder code generator, and are documented in Developing S-Functions.
You need to use the set of macros rtmGetxxx and rtmSetxxx to access the real-time model data structure, which is specific to the Simulink Coder product. The rtModel is an optimized data structure that replaces SimStruct as the top level data structure for a model. The rtmGetxxx and rtmSetxxx macros are used in the generated code as well as from the main.c or main.cpp module. If you are customizing main.c or main.cpp (either a static file or a generated file), you need to use rtmGetxxx and rtmSetxxx instead of the ssSetxxx and ssGetxxx macros.
Usage of rtmGetxxx and rtmSetxxx macros is the same as for the ssSetxxx and ssGetxxx versions, except that you replace SimStruct S by real-time model data structure rtM. The following table lists rtmGetxxx and rtmSetxxx macros that are used in grt_main.c, grt_main.cpp, grt_malloc_main.c, and grt_malloc_main.cpp.
Macros for Accessing the Real-Time Model Data Structure
rtm Macro Syntax | Description |
|---|---|
Get the derivatives of a block's continuous states | |
Return the pointer of vector that store all sample time offset of the model associated with rtM | |
Get the number of sample times that a block has | |
Return a pointer of NumSampleTime × NumSampleTime matrix | |
Return an external mode information data structure of the model. This data structure is used internally for external mode. | |
Return a data structure used by Simulink Coder logging. Internal use. | |
Return a data structure of Simulink Coder real-time model methods information. Internal use. | |
Return data structure containing solver information of the model. Internal use. | |
Return a pointer of Sample Hit flag vector | |
Get a task's sample time | |
Get pointer to a task's sample time | |
Get pointer to a task's ID | |
Return simulation step type ID (MINOR_TIME_STEP, MAJOR_TIME_STEP) | |
Return the fundamental step size of the model | |
Get the current simulation time | |
Set the time of the next sample hit | |
Get the current time for the current task | |
Get the simulation stop time | |
Set the simulation stop time | |
Return a data structure used by timing engine of the model. Internal use. | |
Return a pointer of the current time | |
Get the simulation start time | |
Determine whether a task is continuous | |
Determine whether the simulation is in a major step | |
Determine whether the sample time is hit |
For additional details on usage, see S-Function SimStruct Functions — Alphabetical List in the Simulink Developing S-Functions documentation.
Making Pre-R2012a Custom GRT-Based Targets ERT-Compatible. If you developed a GRT-based custom target in a release before R2012a, it is simple to make your target ERT compatible. By doing so, you can take advantage of many efficiencies.
There are several approaches to ERT compatibility:
If your installation does not include an Embedded Coder license, you can convert a GRT-based target as described in Converting Your Target to Use rtModel. This enables your custom target to support all current GRT features, including back end Embedded-C code generation.
If your installation includes an Embedded Coder license, you can do either of the following:
Create an ERT-based target, but continue to use your customized version of grt_main.c or grt_main.cpp module. To do this, you can configure the ERT target to generate a pre-R2012a GRT calling interface, as described in Generating Pre-R2012a GRT Wrapper Code. This lets your target support the full ERT feature set, without changing your GRT-based run-time interface.
Reimplement your custom target as a completely ERT-based target, including use of an ERT generated main program. This approach lets your target support the full ERT feature set, without the overhead caused by wrapper calls.
Note If you intend to use custom storage classes (CSCs) with a custom target, you must use an ERT-based target. See Custom Storage Classes in the Embedded Coder documentation for detailed information on CSCs. |
For details on how GRT targets are made call-compatible with previous Simulink Coder product versions, see Using the Real-Time Model Data Structure.
Converting Your Target to Use rtModel. The real-time model data structure (rtModel) encapsulates model-specific information in a much more compact form than the SimStruct. Many ERT-related efficiencies depend on generation of rtModel rather than SimStruct, including
Integer absolute and elapsed timing services
Independent timers for asynchronous tasks
Generation of improved C API code for signal, state, and parameter monitoring
Pruning the data structure to minimize its size (ERT-derived targets only)
To take advantage of such efficiencies, you must update your GRT-based target to use the rtModel (unless you already did so for Release 13). The conversion requires changes to your system target file, template makefile, and main program module.
The following changes to the system target file and template makefile are required to use rtModel instead of SimStruct:
In the system target file, add the following global variable assignment:
%assign GenRTModel = TLC_TRUE
In the template makefile, define the symbol USE_RTMODEL. See one of the GRT template makefiles for an example.
The following changes to your main program module (that is, your customized version of grt_main.c or grt_main.cpp) are required to use rtModel instead of SimStruct:
Include rtmodel.h instead of simstruc.h.
Since the rtModel data structure has a type that includes the model name, define the following macros at the top of the main program file:
#define EXPAND_CONCAT(name1,name2) name1 ## name2 #define CONCAT(name1,name2) EXPAND_CONCAT(name1,name2) #define RT_MODEL CONCAT(MODEL,_rtModel)
Change the extern declaration for the function that creates and initializes the SimStruct to
extern RT_MODEL *MODEL(void);
Change the definitions of rt_CreateIntegrationData and rt_UpdateContinuousStates to be as shown in the Release 14 version of grt_main.c.
Change all function prototypes to have the argument 'RT_MODEL' instead of the argument 'SimStruct'.
The prototypes for the functions rt_GetNextSampleHit, rt_UpdateDiscreteTaskSampleHits, rt_UpdateContinuousStates, rt_UpdateDiscreteEvents, rt_UpdateDiscreteTaskTime, and rt_InitTimingEngine have changed. Change their names to use the prefix rt_Sim instead of rt_ and then change the arguments you pass in to them.
See the Release 14 version of grt_main.c for the list of arguments passed in to each function.
Modify all macros that refer to the SimStruct to now refer to the rtModel. SimStruct macros begin with the prefix ss, whereas rtModel macros begin with the prefix rtm. For example, change ssGetErrorStatus to rtmGetErrorStatus.
Generating Pre-R2012a GRT Wrapper Code. The Simulink Coder product supports the Classic call interface model option. When this option is selected, the Simulink Coder product generates model function calls that are compatible with the main program module of the pre-R2012a GRT target (grt_main.c or grt_main.cpp). These calls act as wrappers that interface to code generated with R2012a or higher.
This option provides a quick way to use code generated with R2012a or higher with a main program module based on pre-R2012a grt_main.c or grt_main.cpp.
The Simulink Coder product provides five different code formats. Each code format specifies a framework for code generation suited for specific applications. The five code formats and corresponding application areas are
Real-time — Rapid prototyping
Real-time malloc — Rapid prototyping
S-function — Creating proprietary S-function MEX-file objects, code reuse, and speeding up your simulation
Model reference — Creating MEX-file objects from entire models that other models can use, sometimes in place of S-functions
Embedded C — Deeply embedded systems
This chapter discusses the relationship of code formats to the available target configurations, and factors you should consider when choosing a code format and target. This chapter also summarizes the real-time, real-time malloc, S-function, model referencing, and embedded C/C++ code formats.
The Simulink Coder software generates two styles of code. One code style is suitable for rapid prototyping (and simulation by using code generation). The other style is suitable for embedded applications. This chapter discusses the program architecture, that is, the structure of code generated by the Simulink Coder code generator, associated with these two styles of code. The next table classifies the targets shipped with the product. For related details about code style and target characteristics, see Types of Target Code Formats.
Code Styles Listed by Target
Target | Code Style (Using C or C++ Unless Noted) |
|---|---|
Embedded Coder embedded real-time (ERT) target | Embedded — Useful as a starting point when using generated C/C++ code in an embedded application (often referred to as a production code target). |
Simulink Coder Generic real-time (GRT) target | Rapid prototyping — Use as a starting point for creating a rapid prototyping target that does not use real-time operating system tasking primitives, and for verifying the generated code on your workstation. Uses components of ERT, with a different calling interface. |
Real-time malloc target | Rapid prototyping — Similar to the generic real-time (GRT) target except that this target allocates all model working memory dynamically rather than statically declaring it in advance. |
Rapid simulation target (RSim) | Rapid prototyping — Non-real-time simulation of your model on your workstation. Useful as a high-speed or batch simulation tool. |
S-function target | Rapid prototyping — Creates a C MEX S-function for simulation of your model within another Simulink model. |
Tornado (VxWorks) real-time target[a] | Rapid prototyping — Runs model in real time using the VxWorks real-time operating system tasking primitives. Also useful as a starting point for targeting a real-time operating system. |
Real-Time Windows Target | Rapid prototyping — Runs model in real time at interrupt level while your PC is running a Microsoft Windows environment in the background. |
xPC Target | Rapid prototyping — Runs model in real time on target PC running the xPC Target kernel. |
[a] Tornado and VxWorks are registered trademarks of Wind River Systems, Inc. | |
Third-party vendors supply additional targets for the Simulink Coder product. Generally, these can be classified as rapid prototyping targets. For more information about third-party products, see the MathWorks Connections Program Web page: http://www.mathworks.com/products/connections.
This chapter is divided into three sections. The first section discusses model execution, the second section discusses the rapid prototyping style of code, and the third section discusses the embedded style of code.
Because GRT targets now use Embedded-C code format, existing applications that depend on the RealTime code format's calling interface could have compatibility issues. To address this, a set of macros is generated (in model.h) that maps Embedded-C data structures to the identifiers that RealTime code format used. The following, which can be found in any model.h file created for a GRT target, describes these identifier mappings:
/* Backward compatible GRT Identifiers */ #define rtB model_B #define BlockIO BlockIO_model #define rtXdot model_Xdot #define StateDerivatives StateDerivatives_model #define tXdis model_Xdis #define StateDisabled StateDisabled_model #define rtY model_Y #define ExternalOutputs ExternalOutputs_model #define rtP model_P #define Parameters Parameters_model
Since the GRT target now uses the Embedded-C code format for back end code generation, many Embedded-C optimizations are available to all Simulink Coder users. In general, the GRT and ERT targets now have many more common features, but the ERT target offers additional controls for common features. The availability of features is now determined by licensing, rather than being tied to code format. The following table compares features available with a Simulink Coder license with those available under an Embedded Coder license:
Comparison of Features Licensed with the Simulink Coder Product Versus the Embedded Coder Product
Feature | Simulink Coder License | Embedded Coder License |
|---|---|---|
rtModel data structure |
|
|
Custom storage classes (CSCs) | Code generation ignores CSCs; objects are assigned a CSC default to Auto storage class | Code generation with CSCs is supported |
HTML code generation report | Basic HTML code generation report | Enhanced report with additional detail and hyperlinks to the model |
Symbol formatting | Symbols (for signals, parameters and so on) are generated in accordance with hard-coded default | Detailed control over generated symbols. |
User-defined maximum identifier length for generated symbols | Supported | Supported |
Generation of terminate function | Always generated | Option to suppress terminate function |
Combined output/update function | Separate output/update functions are generated | Option to generate combined output/update function |
Optimized data initialization | Not available | Options to suppress generation of unnecessary initialization code for zero-valued memory, I/O ports, and so on |
Comments generation | Basic options to include or suppress comment generation | Options to include Simulink block descriptions, Stateflow object descriptions, and Simulink data object descriptions in comments |
Module Packaging Features (MPF) | Not supported | Extensive code customization features (see the Embedded Coder documentation) |
Target-optimized data types header file | Requires full tmwtypes.h header file | Generates optimized rtwtypes.h header file, including definitions required by the target |
User-defined types | User-defined types default to base types in code generation | User defined data type aliases are supported in code generation |
Rate grouping | Not supported | Supported |
Auto-generation of main program module | Not supported; static main program module is provided. | Automated and customizable generation of main program module is supported (static main program also available) |
Reusable (multi-instance) code generation with static memory allocation | Not supported | Option to generate reusable code |
Software constraint options | Support for floating point, complex, and nonfinite numbers is always enabled | Options to enable or disable support for floating-point, complex, and nonfinite numbers |
Application life span | Defaults to inf | User-specified; determines most efficient word size for integer timers |
Software-in-the-loop (SIL) testing | Model reference simulation target can be used for SIL testing | Additional SIL testing support by using auto-generation of SIL block |
ANSI[a] -C/C++ code generation | Supported | Supported |
ISO®[b] -C/C++ code generation | Supported | Supported |
GNU®[c] -C/C++ code generation | Supported | Supported |
Generate scalar inlined parameters as #DEFINE statements | Not supported | Supported |
MAT-file variable name modifier | Supported | Supported |
Data exchange: C API, external mode, ASAP2 | Supported | Supported |
[a] ANSI is a registered trademark of the American National Standards Institute, Inc. [b] ISO is a registered trademark of the International Organization for Standardization. [c] GNU is a registered trademark of the Free Software Foundation. | ||
The first step to configuring a model for Simulink Coder code generation is to choose and configure a code generation target. When you select a target, other model configuration parameters change automatically to best serve requirements of the target. For example:
Code interface parameters
Build process parameters, such as the template make file
Target hardware parameters, such as word size and byte ordering
Use the Browse button on the Code Generation pane to open the System Target File Browser. The browser lets you select a preset target configuration consisting of a system target file, template makefile, and make command. For a complete list of available target configurations, see Available Targets.
If you select a target configuration by using the System Target File Browser, your selection appears in the System target file field (target.tlc).
If you are using a target configuration that does not appear in the System Target File Browser, enter the name of your system target file in the System target file field. Click Apply or OK to configure for that target.
You also can select a target programmatically from MATLAB code, as described in Selecting a System Target File Programmatically.
After selecting a target, you can modify model configuration parameter settings.
If you want to switch between different targets in a single workflow for different code generation purposes (for example, rapid prototyping versus product code deployment), set up different configuration sets for the same model and switch the active configuration set for the current operation. For more information on how to set up configuration sets and change the active configuration set, see Manage a Configuration Set in the Simulink documentation.
To select a target configuration using the System Target File Browser,
Click Code Generation on the Configuration Parameters dialog box. The Code Generation pane appears.
Click the Browse button next to the System target file field. This opens the System Target File Browser. The browser displays a list of all currently available target configurations, including customizations. When you select a target configuration, the Simulink Coder software automatically chooses the system target file, template makefile, and make command for that configuration.
The next step shows the System Target File Browser with the generic real-time target selected.
Click the desired entry in the list of available configurations. The background of the list box turns yellow to indicate an unapplied choice has been made. To apply it, click Apply or OK.
System Target File Browser

When you choose a target configuration, the Simulink Coder software automatically chooses the system target file, template makefile, and make command for that configuration, and displays them in the System target file field. The description of the target file from the browser is placed below its name in the general Code Generation pane.
Simulink models store model-wide parameters and target-specific data in configuration sets. Every configuration set contains a component that defines the structure of a particular target and the current values of target options. Some of this information is loaded from a system target file when you select a target using the System Target File Browser. You can configure models to generate alternative target code by copying and modifying old or adding new configuration sets and browsing to select a new target. Subsequently, you can interactively select an active configuration from among these sets (only one configuration set can be active at a given time).
Scripts that automate target selection need to emulate this process.
To program target selection
Obtain a handle to the active configuration set with a call to the getActiveConfigSet function.
Define string variables that correspond to the required Simulink Coder system target file, template makefile, and make command settings. For example, for the ERT target, you would define variables for the strings 'ert.tlc', 'ert_default_tmf', and 'make_rtw'.
Select the system target file with a call to the switchTarget function. In the function call, specify the handle for the active configuration set and the system target file.
Set the TemplateMakefile and MakeCommand configuration parameters to the corresponding variables created in step 2.
For example:
cs = getActiveConfigSet(model); stf = 'ert.tlc'; tmf = 'ert_default_tmf'; mc = 'make_rtw'; switchTarget(cs,stf,[]); set_param(cs,'TemplateMakefile',tmf); set_param(cs,'MakeCommand',mc);
The Simulink Coder product includes a set of built-in template makefiles that are designed to build programs for specific targets.
There are two types of template makefiles:
Compiler-specific template makefiles are designed for use with a particular compiler or development system.
By convention, compiler-specific template makefiles are named according to the target and compiler (or development system). For example, grt_vc.tmf is the template makefile for building a generic real-time program under the Visual C++ compiler; ert_lcc.tmf is the template makefile for building an Embedded Coder program under the Lcc compiler.
Default template makefiles make your model designs more portable, by choosing the compiler-specific makefile and compiler for your installation. Choose and Configure a Compiler describes the operation of default template makefiles in detail.
Default template makefiles are named target_default_tmf. They are MATLAB language files that, when run, select the TMF for the specified target configuration. For example, grt_default_tmf is the default template makefile for building a generic real-time program; ert_default_tmf is the default template makefile for building an Embedded Coder program.
You can supply options to makefiles by using arguments to the Make command field in the general Code Generation pane of the Configuration Parameters dialog box. Append the arguments after make_rtw (or make_xpc or other make command), as in the following example:
make_rtw OPTS="-DMYDEFINE=1"
The syntax for make command options differs slightly for different compilers.
Complete details on the structure of template makefiles are provided in the Embedded Coder documentation. This information is provided for those who want to customize template makefiles. This section describes compiler-specific template makefiles and common options you can use with each.
Note To control compiler optimizations for your Simulink Coder makefile build at the Simulink GUI level, use the Compiler optimization level option on the Code Generation pane of the Configuration Parameters dialog box. The Compiler optimization level option provides
If you specify compiler options for your Simulink Coder makefile build using OPT_OPTS, MEX_OPTS (except MEX_OPTS="-v"), or MEX_OPT_FILE, the value of Compiler optimization level is ignored and a warning is issued about the ignored parameter. |
The template makefiles for UNIX platforms are designed to be used with the Free Software Foundation's GNU Make. These makefile are set up to conform to the guidelines specified in the IEEE®[7] Std 1003.2-1992 (POSIX) standard.
ert_unix.tmf
grt_malloc_unix.tmf
grt_unix.tmf
rsim_unix.tmf
rtwsfcn_unix.tmf
You can supply options by using arguments to the make command.
OPTS — User-specific options, for example,
make_rtw OPTS="-DMYDEFINE=1"
OPT_OPTS— Optimization options. Default is -O. To enable debugging specify as OPT_OPTS=-g. Because of optimization problems in IBM_RS, the default is no optimization.
CPP_OPTS — C++ compiler options.
USER_SRCS — Additional user sources, such as files used by S-functions.
USER_INCLUDES — Additional include paths, for example,
USER_INCLUDES="-Iwhere-ever -Iwhere-ever2"
These options are also documented in the comments at the head of the respective template makefiles.
The Simulink Coder product offers two sets of template makefiles designed for use with the Visual C++ compiler.
To build an executable within the Simulink Coder build process, use one of the target_vc.tmf template makefiles:
ert_vc.tmf
grt_malloc_vc.tmf
grt_vc.tmf
rsim_vc.tmf
rtwsfcn_vc.tmf
You can supply options by using arguments to the make command.
OPT_OPTS — Optimization option. Default is -O2. To enable debugging specify as OPT_OPTS=-Zi.
OPTS — User-specific options.
CPP_OPTS — C++ compiler options.
USER_SRCS — Additional user sources, such as files used by S-functions.
USER_INCLUDES — Additional include paths, for example,
USER_INCLUDES="-Iwhere-ever -Iwhere-ever2"
These options are also documented in the comments at the head of the respective template makefiles.
Visual C++ Code Generation Only. To create a Visual C++ project makefile (model.mak) without building an executable, use one of the target_msvc.tmf template makefiles:
ert_msvc.tmf
grt_malloc_msvc.tmf
grt_msvc.tmf
These template makefiles are designed to be used with nmake, which is bundled with the Visual C++ compiler.
You can supply the following options by using arguments to the nmake command:
OPTS — User-specific options, for example,
make_rtw OPTS="/D MYDEFINE=1"
USER_SRCS — Additional user sources, such as files used by S-functions.
USER_INCLUDES — Additional include paths, for example,
USER_INCLUDES="-Iwhere-ever -Iwhere-ever2"
These options are also documented in the comments at the head of the respective template makefiles.
The Simulink Coder product provides template makefiles to create an executable for the Microsoft Windows platform using Watcom C/C++. These template makefiles are designed to be used with wmake, which is bundled with Watcom C/C++.
Note The Watcom C compiler is no longer available from the manufacturer. However, the Simulink Coder product continues to ship with Watcom-related template makefiles. |
ert_watc.tmf
grt_malloc_watc.tmf
grt_watc.tmf
rsim_watc.tmf
rtwsfcn_watc.tmf
You can supply options by using arguments to the make command. Note that the location of the quotes is different from the other compilers and make utilities discussed in this chapter.
OPTS — User-specific options, for example,
make_rtw "OPTS=-DMYDEFINE=1"
OPT_OPTS — Optimization options. The default optimization option is -oxat. To turn off optimization and add debugging symbols, specify the -d2 compiler switch in the make command, for example,
make_rtw "OPT_OPTS=-d2"
CPP_OPTS — C++ compiler options.
USER_OBJS — Additional user objects, such as files used by S-functions.
USER_PATH — The folder path to the source (.c or .cpp) files that are used to create any .obj files specified in USER_OBJS. Multiple paths must be separated with a semicolon. For example,
USER_PATH="path1;path2"
USER_INCLUDES — Additional include paths, for example,
USER_INCLUDES="-Iinclude-path1 -Iinclude-path2"
These options are also documented in the comments at the head of the respective template makefiles.
The Simulink Coder product provides template makefiles to create an executable for the Windows platform using Lcc compiler Version 2.4 and GNU Make (gmake).
ert_lcc.tmf
grt_lcc.tmf
grt_malloc_lcc.tmf
rsim_lcc.tmf
rtwsfcn_lcc.tmf
You can supply options by using arguments to the make command:
OPTS — User-specific options, for example,
make_rtw OPTS="-DMYDEFINE=1"
OPT_OPTS — Optimization options. Default is none. To enable debugging, specify -g4 in the make command:
make_rtw OPT_OPTS="-g4"
CPP_OPTS — C++ compiler options.
USER_SRCS — Additional user sources, such as files used by S-functions.
USER_INCLUDES — Additional include paths, for example,
USER_INCLUDES="-Iwhere-ever -Iwhere-ever2"
For Lcc, have a / as file separator before the filename instead of a \, for example, d:\work\proj1/myfile.c.
These options are also documented in the comments at the head of the respective template makefiles.
The Simulink Coder software is able to handle path names that include spaces. Spaces might appear in the path from several sources:
Your MATLAB installation folder
The current MATLAB folder in which you initiate a build
A compiler you are using for a Simulink Coder build
If your work environment includes one or more of the preceding scenarios, use the following support mechanisms as they apply::
Add the following code to your template makefile (.tmf):
ALT_MATLAB_ROOT = |>ALT_MATLAB_ROOT<| ALT_MATLAB_BIN = |>ALT_MATLAB_BIN<| !if "$(MATLAB_ROOT)" != "$(ALT_MATLAB_ROOT)" MATLAB_ROOT = $(ALT_MATLAB_ROOT) !endif !if "$(MATLAB_BIN)" != "$(ALT_MATLAB_BIN)" MATLAB_BIN = $(ALT_MATLAB_BIN) !endif
This code replaces MATLAB_ROOT with ALT_MATLAB_ROOT when the values of the two tokens are not equal, indicating the path for your MATLAB installation folder includes spaces. Likewise, ALT_MATLAB_BIN replaces MATLAB_BIN.
Note the preceding code is specific to nmake. See the supplied Simulink Coder template make files for platform-specific examples.
When using operating system commands, such as system or dos, enclose path that specify executables or command parameters in double quotes (" "). For example,
system('dir "D:\Applications\Common Files"')You can create your own system target files to build custom targets that interface with external code or operating environments.
See Custom Target Development for details and examples showing how to make your custom targets appear in the System Target File Browser and display relevant controls in panes of the Configuration Parameters dialog box.
The Configuration Parameters dialog Hardware Implementation pane provides options that you can use to describe hardware properties, such as data size and byte ordering, and compiler behavior details that may vary with the compiler, such as integer rounding. The Hardware Implementation pane contains two subpanes:
Embedded Hardware — Describes the embedded target hardware and the compiler that you will use with it. This information affects both simulation and code generation.
Emulation Hardware — Describes the emulation target hardware and the compiler that you will use with it. This information affects only code generation.
The two subpanes provide identical options and value choices. By default, the Embedded Hardware subpane initially looks like this:

The default assumption is that the embedded target and emulation target are the same, so the Emulation Hardware subpane by default does not need to specify anything and contains only a checked option labeled None. Code generated under this configuration will be suitable for production use, or for testing in an environment identical to the production environment.
If you clear the check box, the Emulation Hardware subpane appears, initially showing the same values as the Embedded Hardware subpane. If you change any of these values, then generate code, the code will be able to execute in the environment specified by the Emulation Hardware subpane, but will behave as if it were executing in the environment specified by the Embedded Hardware subpane. See Configure Emulation Hardware Characteristics for details.
If you have used the Code Generation pane General tab to specify a System target file, and the target file specifies a default microprocessor and its hardware properties, the default and properties appear as initial values in the Hardware Implementation pane.
Options with only one possible value cannot be changed. Any option that has more than one possible value provides a list of legal values. If you specify any hardware properties manually, check carefully that their values are consistent with the system target file. Otherwise, the generated code may fail to compile or execute, or may execute but give incorrect results.
Note Hardware Implementation pane options do not control hardware or compiler behavior in any way. Their purpose is solely to describe hardware and compiler properties to MATLAB software, which uses the information to generate code for the platform thatruns as efficiently as possible, and gives bit-true agreement for the results of integer and fixed-point operations in simulation, production code, and test code. |
The rest of this section describes the options in the Embedded Hardware and Emulation Hardware subpanes. Subsequent sections describe considerations that apply only to one or the other subpane. For more about Hardware Implementation options, see Hardware Implementation Pane. To see an example of Hardware Implementation pane capabilities, run the rtwdemo_targetsettings demo.
The Device vendor option gives the name of the device vendor. To set the option, select a vendor name from the Device vendor menu. Your selection of vendor will determine the available device values in the Device type list. If the desired vendor name does not appear in the menu, select Generic and then use the Device type option to further specify the device.
Note
|
The Device type option selects a hardware device among the supported devices listed for your Device vendor selection. To set the option, select a microprocessor name from the Device type menu. If the desired microprocessor does not appear in the menu, change the Device vendor to Generic.
If you specified Device vendor as Generic, examine the listed device descriptions and select the device type that matches your hardware. If no available device type matches, select Custom.
If you select a device type for which the target file specifies default hardware properties, the properties appear as initial values in the subpane. Options with only one possible value cannot be changed. Any option that has more than one possible value provides a list of legal values. Select values for your hardware. If the device type is Custom, all options can be set, and each option has a list of all possible values.
To add Device vendor and Device type values to the default set that is displayed on the Hardware Implementation pane, you can use a hardware device registration API provided by the Simulink Coder software.
To use this API, you create an sl_customization.m file, located in your MATLAB path, that invokes the registerTargetInfo function and fills in a hardware device registry entry with device information. The device information will be registered with Simulink software for each subsequent Simulink session. (To register your device information without restarting MATLAB, issue the MATLAB command sl_refresh_customizations.)
For example, the following sl_customization.m file adds device vendor MyDevVendor and device type MyDevType to the Simulink device lists.
function sl_customization(cm)
cm.registerTargetInfo(@loc_register_device);
end
function thisDev = loc_register_device
thisDev = RTW.HWDeviceRegistry;
thisDev.Vendor = 'MyDevVendor';
thisDev.Type = 'MyDevType';
thisDev.Alias = {};
thisDev.Platform = {'Prod', 'Target'};
thisDev.setWordSizes([8 16 32 32 32]);
thisDev.LargestAtomicInteger = 'Char';
thisDev.LargestAtomicFloat = 'None';
thisDev.Endianess = 'Unspecified';
thisDev.IntDivRoundTo = 'Undefined';
thisDev.ShiftRightIntArith = true;
thisDev.setEnabled({'IntDivRoundTo'});
endIf you subsequently select the device in the Hardware Implementation pane, it is displayed as follows:

To register multiple devices, you can specify an array of RTW.HWDeviceRegistry objects in your sl_customization.m file. For example,
function sl_customization(cm) cm.registerTargetInfo(@loc_register_device); end function thisDev = loc_register_device thisDev(1) = RTW.HWDeviceRegistry; thisDev(1).Vendor = 'MyDevVendor'; thisDev(1).Type = 'MyDevType1'; ... thisDev(4) = RTW.HWDeviceRegistry; thisDev(4).Vendor = 'MyDevVendor'; thisDev(4).Type = 'MyDevType4'; ... end
The following table lists the RTW.HWDeviceRegistry properties that you can specify in the registerTargetInfo function call in your sl_customization.m file.
| Property | Description |
|---|---|
| Vendor | String specifying the Device vendor value for your hardware device. |
| Type | String specifying the Device type value for your hardware device. |
| Alias | Cell array of strings specifying any aliases or legacy names that users might specify that should resolve to this device. Specify each alias or legacy name in the format 'Vendor->Type'. (Embedded Coder software provides the utility functions RTW.isHWDeviceTypeEq and RTW.resolveHWDeviceType for detecting and resolving alias values or legacy values when testing user-specified values for the target device type.) |
| Platform | Cell array of enumerated string values specifying whether this device should be listed in the Embedded hardware subpane ({'Prod'}), the Emulation hardware subpane ({'Target'}), or both ({'Prod', 'Target'}). |
| setWordSizes | Array of integer sizes to associate with the Number of bits parameters char, short, int, long, and native word size, respectively. |
| LargestAtomicInteger | String specifying an enumerated value for the Largest atomic size: integer parameter: 'Char', 'Short','Int', or 'Long'. |
| LargestAtomicFloat | String specifying an enumerated value for the Largest atomic size: floating-point parameter: 'Float', 'Double', or 'None'. |
| Endianess | String specifying an enumerated value for the Byte ordering parameter: 'Unspecified', 'Little' for little Endian, or 'Big' for big Endian. |
| IntDivRoundTo | String specifying an enumerated value for the Signed integer division rounds to parameter: 'Zero', 'Floor', or 'Undefined'. |
| ShiftRightIntArith | Boolean value specifying whether your compiler implements a signed integer right shift as an arithmetic right shift (true) or not (false). |
| setEnabled | Cell array of strings specifying which device properties should be enabled (modifiable) in the Hardware Implementation pane when this device type is selected. In addition to the 'Endianess', 'IntDivRoundTo', and 'ShiftRightIntArith' properties listed above, you can enable individual Number of bits parameters using the property names 'BitPerChar', 'BitPerShort', 'BitPerInt', 'BitPerLong', and 'NativeWordSize'. |
The Number of bits options describe the native word size of the microprocessor, and the bit lengths of char, short, int, and long data. For code generation to succeed:
The bit lengths must be such that char <= short <= int <= long.
All bit lengths must be multiples of 8, with a maximum of 32.
The bit length for long data must not be less than 32.
Simulink Coder integer type names are defined in the file rtwtypes.h. The values that you provide must be consistent with the word sizes as defined in the compiler's limits.h header file. The following table lists the standard Simulink Coder integer type names and maps them to the corresponding Simulink names.
| Simulink Coder Integer Type | Simulink Integer Type |
|---|---|
| boolean_T | boolean |
| int8_T | int8 |
| uint8_T | uint8 |
| int16_T | int16 |
| uint16_T | uint16 |
| int32_T | int32 |
| uint32_T | uint32 |
If no ANSI C type with a matching word size is available, but a larger ANSI C type is available, the Simulink Coder code generator uses the larger type for int8_T, uint8_T, int16_T, uint16_T, int32_T, and uint32_T.
An application can use integer data of any length from 1 (unsigned) or 2 (signed) bits up 32 bits. If the integer length matches the length of an available type, the Simulink Coder code generator uses that type. If no matching type is available, the code generator uses the smallest available type that can hold the data, generating code that never uses unnecessary higher-order bits. For example, on a target that provided 8-bit, 16-bit, and 32-bit integers, a signal specified as 24 bits would be implemented as an int32_T or uint32_T.
Code that uses emulated integer data is not maximally efficient, but can be useful during application development for emulating integer lengths that are available only on production hardware. The use of emulation does not affect the results of execution.
The Byte ordering option specifies whether the target hardware uses Big Endian (most significant byte first) or Little Endian (least significant byte first) byte ordering. If left as Unspecified, the Simulink Coder software generates code that determines the endianness of the target; this is the least efficient option.
ANSI C does not completely define the rounding technique to be used when dividing one signed integer by another, so the behavior is implementation-dependent. If both integers are positive, or both are negative, the quotient must round down. If either integer is positive and the other is negative, the quotient can round up or down.
The Signed integer division rounds to parameter tells the Simulink Coder code generator how the compiler rounds the result of signed integer division. Providing this information does not affect the operation of the compiler, it only describes that behavior to the code generator, which uses the information to optimize code generated for signed integer division. The parameter options are:
Zero — If the quotient is between two integers, the compiler chooses the integer that is closer to zero as the result.
Floor — If the quotient is between two integers, the compiler chooses the integer that is closer to negative infinity.
Undefined — Choose this option if neither Zero nor Floor describes the compiler's behavior, or if that behavior is unknown.
The following table illustrates the compiler behavior that corresponds to each of these three options:
| N | D | Ideal N/D | Zero | Floor | Undefined |
|---|---|---|---|---|---|
33 | 4 | 8.25 | 8 | 8 | 8 |
-33 | 4 | -8.25 | -8 | -9 | -8 or -9 |
33 | -4 | -8.25 | -8 | -9 | -8 or -9 |
-33 | -4 | 8.25 | 8 | 8 | 8 or 9 |
Note Select Undefined only as a last resort. When the code generator does not know the signed integer division rounding behavior of the compiler, it generates extra code. |
The compiler's implementation for signed integer division rounding can be obtained from the compiler documentation, or by experiment if no documentation is available.
ANSI C does not define the behavior of right shifts on negative integers, so the behavior is implementation-dependent. The Shift right on a signed integer as arithmetic shift parameter tells the Simulink Coder code generator how the compiler implements right shifts on negative integers. Providing this information does not affect the operation of the compiler, it only describes that behavior to the code generator, which uses the information to optimize the code generated for arithmetic right shifts.
Select the option if the C compiler implements a signed integer right shift as an arithmetic right shift, and clear the option otherwise. An arithmetic right shift fills bits vacated by the right shift with the value of the most significant bit, which indicates the sign of the number in twos complement notation. The option is selected by default. If your compiler handles right shifts as arithmetic shifts, this is the preferred setting.
When the option is selected, the Simulink Coder software generates simple efficient code whenever the Simulink model performs arithmetic shifts on signed integers.
When the option is cleared, the Simulink Coder software generates fully portable but less efficient code to implement right arithmetic shifts.
The compiler's implementation for arithmetic right shifts can be obtained from the compiler documentation, or by experiment if no documentation is available.
Configure Emulation and Embedded Target Hardware documents the options available on the Hardware Implementation subpanes. This section describes considerations that apply only to the Embedded Hardware subpane. When you use this subpane, keep the following in mind:
Code generation targets can have word sizes and other hardware characteristics that differ from the MATLAB host. Furthermore, code can be prototyped on hardware that is different from either the deployment target or the MATLAB host. The Simulink Coder code generator takes these differences into account when generating code.
The Simulink product uses some of the information in the Embedded Hardware subpane to get the same results from simulation without code generation as executing generated code, including detecting error conditions that could arise on the target hardware, such as hardware overflow.
The Simulink Coder software generates code that produces bit-true agreement with Simulink results for integer and fixed-point operations. Generated code that emulates unavailable data lengths runs less efficiently than it would without emulation, but the emulation does not affect bit-true agreement with Simulink for integer and fixed-point results.
If you change targets at any point during application development, reconfigure the hardware implementation parameters for the new target before generating or regenerating code. Bit-true agreement for the results of integer and fixed-point operations in simulation, production code, and test code might not occur when code executes on hardware for which it was not generated.
Use the Integer rounding mode parameter on your model's blocks to simulate the rounding behavior of the C compiler that you intend to use to compile code generated from the model. This setting appears on the Signal Attributes pane of the parameter dialog boxes of blocks that can perform signed integer arithmetic, such as the Product and n-D Lookup Table blocks.
For most blocks, the value of Integer rounding mode completely defines rounding behavior. For blocks that support fixed-point data and the Simplest rounding mode, the value of Signed integer division rounds to also affects rounding. For details, see Rounding in the Simulink Fixed Point User's Guide.
When models contain Model blocks, all models that they reference must be configured to use identical hardware settings.
Configure Emulation and Embedded Target Hardware documents the options available on the Hardware Implementation subpanes. This section describes considerations that apply only to the Emulation Hardware subpane.
Note (If the Emulation Hardware subpane contains a button labeled Configure current execution hardware device, see Update Hardware Configuration for Models Created Before Release 14, then continue from this point.) |
The default assumption is that the embedded target and emulation target are the same, so the Emulation Hardware subpane by default does not need to specify anything and contains only a selected check box labeled None. Code generated under this configuration will be suitable for production use, or for testing in an environment identical to the production environment.
To generate code that runs on an emulation target for test purposes, but behaves as if it were running on an embedded target in a production application, you must specify the properties of both targets in the Hardware Implementation pane. The Embedded Hardware subpane specifies embedded target hardware properties, as described previously. To specify emulation target properties:
Clear the None option in the Emulation Hardware subpane.
By default, the Hardware Implementation pane now looks like this:

In the Emulation Hardware subpane, specify the properties of the emulation target, using the instructions in Configure Emulation and Embedded Target Hardware
If you have used the Code Generation pane General tab to specify a System target file, and the target file specifies a default microprocessor and its hardware properties, the default and properties appear as initial values in both subpanes of the Hardware Implementation pane.
Options with only one possible value cannot be changed. Any option that has more than one possible value provides a list of legal values. If you specify any hardware properties manually, check carefully that their values are consistent with the system target file. Otherwise, the generated code may fail to compile or execute, or may execute but give incorrect results.
If you do not display the Emulation Hardware subpane, the Simulink and Simulink Coder software defaults every Emulation Hardware option to have the same value as the corresponding Embedded Hardware option. If you hide the Emulation Hardware subpane after setting its values, the values that you specified will be lost. The underlying configuration parameters immediately revert to the values that they had when you exposed the subpane, and these values, rather than the values that you specified, will appear if you re-expose the subpane.
If your model was created before Release 14 and has not been updated, by default the Hardware Implementation pane initially looks like this:

Click Configure current execution hardware device. The Configure current execution hardware device button disappears. The subpane then appears as shown in the first figure in this section. Save your model at this point to avoid redoing Configure current execution hardware device next time you access the Hardware Implementation pane.
Use the Interface pane to control which math library is used at run time, whether to include one of three APIs in generated code, and certain other interface options.
| To... | Select or Enter... |
|---|---|
| Specify the target-specific math library to use when generating code | Select C89/C90 (ANSI), C99 (ISO), GNU99 (GNU), or C++ (ISO) for Code replacement library. (Additional values may be listed for licensed target products, for Embedded Targets and Desktop Targets, or if you have created and registered code replacement libraries with the Embedded Coder product.) Selecting C89/C90 (ANSI) provides the ANSI[a] C set of library functions. For example, selecting C89/C90 (ANSI) would result in generated code that calls sin() whether the input argument is double precision or single precision. However, if you select C99 (ISO), the call instead is to the function sinf(), which is single precision. If your compiler supports the ISO[b] C math extensions, selecting the ISO C library can result in more efficient code. For more information about code replacement libraries, see Selecting and Viewing Code Replacement Libraries. |
| Direct where the Simulink Coder code generator should place fixed-point and other utility code | Select Auto or Shared
location for Shared code placement.
The shared location directs code for utilities to be placed within
the slprj folder in your working folder, which
is used for building model reference targets. If you select Auto,
|
| Specify a string to be added to the variable names used when logging data to MAT-files, to distinguish logging data from Simulink Coder and Simulink applications | Enter a prefix or suffix, such as rt_ or _rt, for MAT-file variable name modifier. The Simulink Coder code generator prefixes or appends the string to the variable names for system outputs, states, and simulation time specified in the Data Import/Export pane. See Logging for information on MAT-file data logging. |
| Specify an API to be included in generated code | Select C API, External mode, or ASAP2 for Interface. When you select C API or External mode, other options appear. C API and External mode are mutually exclusive. However, this is not the case for C API and ASAP2. For more information on working with these interfaces, see Data Interchange Using the C API, Host/Target Communication , and ASAP2 Data Measurement and Calibration. |
[a] ANSI is a registered trademark of the American National Standards Institute, Inc. [b] ISO is a registered trademark of the International Organization for Standardization. | |
Note Before setting Code replacement library, verify that your compiler supports the library you want to use. If you select a parameter value that your compiler does not support, compiler errors can occur. For example, if you select C99 (ISO) and your compiler does not support the ISO C math extensions, compile-time errors likely will occur. |
When the Embedded Coder product is installed on your system, the Code Generation > Interface pane expands to include several additional options. For details, see in the Embedded Coder documentation.
For a summary of option dependencies, see Interface Dependencies.
For descriptions of Code Generation > Interface pane parameters, see Code Generation Pane: Interface in the Simulink Coder reference documentation.
Several parameters available on the Interface pane have dependencies on settings of other parameters. The following table summarizes the dependencies.
| Parameter | Dependencies? | Dependency Details |
|---|---|---|
| Code replacement library | No | |
| Shared code placement | No | |
| Support: floating-point numbers (ERT targets only) | No | |
| Support: non-finite numbers | Yes (ERT targets) No (GRT targets) | For ERT targets, enabled by Support floating-point numbers |
| Support: complex numbers (ERT targets only) | No | |
| Support: absolute time (ERT targets only) | No | |
| Support: continuous time (ERT targets only) | No | |
| Support: non-inlined S-functions (ERT targets only) | Yes | Requires that you enable Support floating-point numbers and Support non-finite numbers |
| Classic call interface | Yes (ERT targets) No (GRT targets) | For ERT targets, requires that you enable Support floating-point numbers and disable Single output/update function |
| Single output/update function (ERT targets only) | Yes | Disable for Classic call interface |
| Terminate function required (ERT targets only) | Yes | |
| Generate reusable code (ERT targets only) | Yes | |
| Reusable code error diagnostic (ERT targets only) | Yes | Enabled by Generate reusable code |
| Pass root-level I/O as (ERT targets only) | Yes | Enabled by Generate reusable code |
| MAT-file logging | Yes | For GRT targets, requires that you enable Support non-finite numbers; for ERT targets, requires that you enable Support floating-point numbers, Support non-finite numbers, and Terminate function required |
| MAT-file file variable name modifier | Yes | Enabled by MAT-file logging |
| Suppress error status in real-time model data structure (ERT targets only) | No | |
| Interface | No | |
| Generate C API for: signals | Yes | Set Interface to C API |
| Generate C API for: parameters | Yes | Set Interface to C API |
| Generate C API for: states | Yes | Set Interface to C API |
| Transport layer | Yes | Set Interface to External mode |
| MEX-file arguments | Yes | Set Interface to External mode |
| Static memory allocation | Yes | Set Interface to External mode |
| Static memory buffer size | Yes | Enable Static memory allocation |
A code replacement library (CRL) is a set of one or more code replacement tables that define the target-specific implementations of math functions and operators to be used in generating code for your Simulink model. The Simulink Coder product provides default CRLs, which you can select from the Code replacement library drop-down list on the Code Generation > Interface pane of the Configuration Parameters dialog box.
| CRL | Description | Contains tables... |
|---|---|---|
| C89/C90 (ANSI) | Generates calls to the ISO/IEC 9899:1990 C standard math library for floating-point functions. | ansi_tfl_table_tmw.mat |
| C99 (ISO) | Generates calls to the ISO/IEC 9899:1999 C standard math library. | iso_tfl_table_tmw.mat ansi_tfl_table_tmw.mat |
| GNU99 (GNU) | Generates calls to the Free Software Foundation's GNU gcc math library, which provides C99 extensions as defined by compiler option -std=gnu99. | gnu_tfl_table_tmw.mat iso_tfl_table_tmw.mat ansi_tfl_table_tmw.mat |
| C++ (ISO) | Generates calls to the ISO/IEC 14882:2003 C++ standard math library. | iso_cpp_tfl_table_tmw.mat private_iso_cpp_tfl_table_tmw.mat iso_tfl_table_tmw.mat ansi_tfl_table_tmw.mat |
CRL tables provide the basis for replacing default math functions and operators in your model code with target-specific code. If you select a library and then hover over the selected library with the cursor, a tool tip is displayed that describes the CRL and lists the code replacement tables it contains. Tables are listed in the order in which they are searched for a function or operator match.

The Simulink Coder product allows you to view the content of CRL code replacement tables using the Code Replacement Viewer, as described in Using the Code Replacement Viewer. If you are licensed to use the Embedded Coder product, you additionally can create and register the code replacement tables that make up a CRL.
Each CRL code replacement table contains one or more table entries, with each table entry representing a potential replacement for a single math function or an operator. Each table entry provides a mapping between a conceptual view of the function or operator (similar to the Simulink block view of the function or operator) and a target-specific implementation of that function or operator.
The conceptual view of a function or operator is represented in a CRL table entry by the following elements, which identify the function or operator entry to the code generation process:
A function or operator key (a function name such as 'cos' or an operator ID string such as 'RTW_OP_ADD')
A set of conceptual arguments that observe Simulink naming ('y1', 'u1', 'u2', ...), along with their I/O types (output or input) and data types
Other attributes, such as fixed-point saturation and rounding characteristics for operators, to identify the function or operator to the code generation process as exactly as required for matching purposes
The target-specific implementation of a function or operator is represented in a CRL table entry by the following elements:
The name of an implementation function (such as 'cos_dbl' or 'u8_add_u8_u8')
A set of implementation arguments, along with their I/O types (output or input) and data types
Parameters providing the build information for the implementation function, including header file and source file names and paths
Additionally, a CRL table entry includes a priority value (0-100, with 0 as the highest priority), which defines the entry's priority relative to other entries in the table.
During code generation for your model, when the code generation process encounters a call site for a math function or operator, it creates and partially populates a CRL entry object, for the purpose of querying the CRL for a replacement function. The information provided for the CRL query includes the function or operator key and the conceptual argument list. The CRL entry object is then passed to the CRL. If the CRL contains a matching table entry, a fully-populated CRL entry, including the implementation function name, argument list, and build information, is returned to the call site and used to generate code.
Within the CRL that is selected for your model, the tables that comprise the CRL are searched in the order in which they are listed (in the left or right pane of the Code Replacement Viewer or in the CRL's Code replacement library tool tip). Within each table, if multiple matches are found for a CRL entry object, priority level determines the match that is returned. A higher-priority (lower-numbered) entry will be used over a similar entry with a lower priority (higher number).
The Code Replacement Viewer allows you to examine the content of CRL code replacement tables. (For an overview of code replacement tables and the information they contain, see the preceding section.) To launch the viewer with all currently registered CRLs displayed, issue the following MATLAB command:
>> RTW.viewTfl

Select the name of a CRL in the left pane, and the viewer displays information about the CRL in the right pane. For example, the tables that make up the CRL are listed in priority order. In the following display, the GNU CRL has been selected.

Click the plus sign (+) next to a CRL name in the left pane to expand its list of tables, and select a table from the list. The viewer displays all function and operator entries in the selected table in the middle pane, along with abbreviated table entry information for each entry. In the following display, the ANSI table has been selected.

The following fields appear in the abbreviated table entry information provided in the middle pane:
| Field | Description |
|---|---|
| Name | Name of the function or ID of the operator to be replaced (for example, cos or RTW_OP_ADD). |
| Implementation | Name of the implementation function, which can match or differ from Name. |
| NumIn | Number of input arguments. |
| In1Type | Data type of the first conceptual input argument. |
| In2Type | Data type of the second conceptual input argument. |
| OutType | Data type of the conceptual output argument. |
| Priority | The entry's search priority, 0-100, relative to other entries of the same name and conceptual argument list within this table. Highest priority is 0, and lowest priority is 100. The default is 100. If the table provides two implementations for a function or operator, the implementation with the higher priority will shadow the one with the lower priority. |
| UsageCount | Not used. |
Select a function or operator entry in the middle pane. The viewer displays detailed information from the table entry in the right pane. In the following display, the second entry for the cos function has been selected.

The following fields appear in the detailed table entry information provided in the right pane.
| Field | Description |
|---|---|
| Description | Text description of the table entry (can be empty). |
| Key | Name of the function or ID of the operator to be replaced (for example, cos or RTW_OP_ADD), and the number of conceptual input arguments. |
| Implementation | Name of the implementation function, and the number of implementation input arguments. |
| Implementation type | Type of implementation: FCN_IMPL_FUNCT for function or FCN_IMPL_MACRO for macro. |
| Saturation mode | Saturation mode supported by the implementation function for an operator replacement: RTW_SATURATE_ON_OVERFLOW, RTW_WRAP_ON_OVERFLOW, or RTW_SATURATE_UNSPECIFIED. |
| Rounding mode | Rounding mode supported by the implementation function for an operator replacement: RTW_ROUND_FLOOR, RTW_ROUND_CEILING, RTW_ROUND_ZERO, RTW_ROUND_NEAREST, RTW_ROUND_NEAREST_ML, RTW_ROUND_SIMPLEST, RTW_ROUND_CONV, or RTW_ROUND_UNSPECIFIED. |
| GenCallback file | Not used. |
| Implementation header | Name of the header file that declares the implementation function. |
| Implementation source | Name of the implementation source file. |
| Priority | The entry's search priority, 0-100, relative to other entries of the same name and conceptual argument list within this table. Highest priority is 0, and lowest priority is 100. The default is 100. If the table provides two implementations for a function or operator, the implementation with the higher priority will shadow the one with the lower priority. |
| Total Usage Count | Not used. |
| Conceptual argument(s) | Name, I/O type (RTW_IO_OUTPUT or RTW_IO_INPUT), and data type for each conceptual argument. |
| Implementation | Name, I/O type (RTW_IO_OUTPUT or RTW_IO_INPUT), and data type for each implementation argument. |
If you select an operator entry, an additional tab containing fixed-point setting information is displayed in the right pane. For example:

The following fields appear in the fixed-point setting information provided in the right pane:
| Field | Description |
|---|---|
| Slopes must be the same | Indicates whether CRL replacement request processing must check that the slopes on all arguments (input and output) are equal. Used with fixed-point addition and subtraction replacement to disregard specific slope and bias values and map relative slope and bias values to a replacement function. |
| Must have zero net bias | Indicates whether CRL replacement request processing must check that the net bias on all arguments is zero. Used with fixed-point addition and subtraction replacement to disregard specific slope and bias values and map relative slope and bias values to a replacement function. |
| Relative scaling factor F | Slope adjustment factor (F) part of the relative scaling factor, F2E, for relative scaling CRL entries. Used with fixed-point multiplication and division replacement to map a range of slope and bias values to a replacement function. |
| Relative scaling factor E | Fixed exponent (E) part of the relative scaling factor, F2E, for relative scaling CRL entries. Used with fixed-point multiplication and division replacement to map a range of slope and bias values to a replacement function. |
[a] UNIX is a registered trademark of The Open Group in the United States and other countries.
[b] Visual C++ is a registered trademark of Microsoft Corporation.
[a] Tornado and VxWorks are registered trademarks of Wind River Systems, Inc.
[a] ANSI is a registered trademark of the American National Standards Institute, Inc.
[b] ISO is a registered trademark of the International Organization for Standardization.
[c] GNU is a registered trademark of the Free Software Foundation.
[7] IEEE is a registered trademark of The Institute of Electrical and Electronics Engineers, Inc.
[a] ANSI is a registered trademark of the American National Standards Institute, Inc.
[b] ISO is a registered trademark of the International Organization for Standardization.
![]() | Application Objectives | Select the Target Language | ![]() |

Learn more about Simulink through this collection of videos, articles, technical literature and the Getting Started with Simulink Guide.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |