| Real-Time Workshop® | ![]() |
This section describes model referencing considerations that apply specifically to code generation by the Real-Time Workshop® software with GRT and ERT system targets. This section assumes that you understand referenced models and their terminology and requirements, as described in Referencing a Model. This section does not repeat information that appears in that chapter.
When generating code for a referenced model hierarchy, the Real-Time Workshop® software generates a stand-alone executable for the top model, and a library module called a model reference target for each referenced model. When the code executes, the top executable invokes the model reference targets as needed to compute the referenced model outputs. Model reference targets are sometimes called Real-Time Workshop targets.
Be careful not to confuse a model reference target (Real-Time Workshop target) with any of these other types of targets:
Hardware target — A platform for which the Real-Time Workshop software generates code
System target — A file that tells the Real-Time Workshop software how to generate code for particular purpose
Rapid Simulation target (RSim) — A system target file supplied with the Real-Time Workshop product
Simulation target — A MEX-file that implements a referenced model that executes with Simulink® Accelerator™ software
The Real-Time Workshop code generator places the code for the top model of a hierarchy in the current working directory, and the code for submodels in a directory named slprj within the current working directory. Subdirectories in slprj provide separate places for different types of files. See Project Directory Structure for Model Reference Targets for details.
By default, the product uses incremental code generation. When generating code, it compares the date, and optionally, the structure of referenced model files with the generated code files to determine whether it is necessary to regenerate model reference targets. You can also force or prevent code generation by using a diagnostic setting Configuration Parameters > Model Referencing > Rebuild options.
In addition to incremental code generation, the Real-Time Workshop software uses incremental loading. The code for a referenced model is not loaded into memory until the code for its parent model executes and needs the outputs of the referenced model. The product then loads the referenced model target and executes. Once loaded, the target remains in memory until it is no longer needed.
Most code generation considerations are the same whether or not a model includes any referenced models: the Real-Time Workshop code generator handles the details automatically insofar as possible. This chapter describes topics that you may need to consider when generating code for a model reference hierarchy.
Custom targets must declare themselves to be model reference compliant if they need to support Model blocks. See Supporting Model Referencing for details.
You can get hands-on experience with creating referenced models and generating code for them by working through the model reference tutorial. See Generating Code for a Referenced Model.
Code for models referenced by using Model blocks is generated in project directories within the current working directory. The top-level project directory is always named /slprj. The next level within slprj contains parallel build area subdirectories.
The following table lists principal project directories and files. In the paths listed, model is the name of the model being used as a referenced model, and target is the system target file acronym (for example, grt, ert , rsim, and so on).
| Directories and Files | Description |
|---|---|
| slprj/sim/model/ | Simulation target files for referenced models |
| slprj/sim/model/tmwinternal | MAT-files used during code generation |
| slprj/target/model/referenced_model_includes | Header files from models referenced by this model |
| slprj/target/model | Model reference target files |
| slprj/target/model/tmwinternal | MAT-files used during code generation |
| slprj/sl_proj.tmw | Marker file |
| slprj/target/_sharedutils | Utility functions for model reference targets, shared across models |
| slprj/sim/_sharedutils | Utility functions for simulation targets, shared across models |
If you are building code for more than one referenced model within the same working directory, model reference files for all such models are added to the existing slprj directory.
By default, the Simulink® engine rebuilds simulation targets as needed before the Real-Time Workshop software generates model reference targets. You can change the rebuild criteria or specify that the engine always or never rebuilds targets. See Rebuild options for details.
The Real-Time Workshop software generates a model reference target directly from the Simulink model. The product automatically generates or regenerates model reference targets as needed.
You can command the Simulink and Real-Time Workshop products to generate a simulation target for an Accelerator mode referenced model, and a model reference target for any referenced model, by executing the slbuild command with appropriate arguments in the MATLAB® Command Window.
The Real-Time Workshop software generates only one model reference target for all instances of a referenced model. See Reusable Code and Referenced Models for details.
You can reduce the time that the Simulink and Real-Time Workshop products spend checking whether any or all simulation targets and model reference targets need to be rebuilt by setting configuration parameter values as follows:
In the top model, set Configuration Parameters > Model Referencing > Rebuild options to If any changes in known dependencies detected. (See Rebuild options.)
In all referenced models throughout the hierarchy, set Configuration Parameters > Diagnostics > Data Validity > Signal resolution to Explicit only. (See Signal resolution.)
These parameter values exist in a referenced model's configuration set, not in the individual Model block, so setting either value for any instance of a referenced model sets it for all instances of that model.
A model reference hierarchy must satisfy various Real-Time Workshop requirements, as described in this section. In addition to these requirements, a model referencing hierarchy to be processed by the Real-Time Workshop software must satisfy:
The Simulink requirements listed in:
The Simulink limitations listed in Limitations on All Model Referencing
The Real-Time Workshop limitations listed in Real-Time Workshop® Model Referencing Limitations
A referenced model uses a configuration set in the same way that any other model does, as described in Configuration Sets. By default, every model in a hierarchy has its own configuration set, which it uses in the same way that it would if the model executed independently.
Because each model can have its own configuration set, configuration parameter values can be different in different models. Furthermore, some parameter values are intrinsically incompatible with model referencing. The response of the Real-Time Workshop software to an inconsistent or unusable configuration parameter depends on the parameter:
Where an inconsistency has no significance, or a trivial resolution exists that carries no risk, the product ignores or resolves the inconsistency without posting a warning.
Where a nontrivial and possibly acceptable solution exists, the product resolves the conflict silently; resolves it with a warning; or generates an error. See Model configuration mismatch for details.
Where no acceptable resolution is possible, the product generates an error. You must then change some or all parameter values to eliminate the problem.
When a model reference hierarchy contains many submodels that have incompatible parameter values, or a changed parameter value must propagate to many submodels, manually eliminating all configuration parameter incompatibilities can be tedious. You can control or eliminate such overhead by using configuration references to assign an externally-stored configuration set to multiple models. See Referencing Configuration Sets for details.
The following tables list configuration parameters that can cause problems if set in certain ways, or if set differently in a referenced model than in a parent model. Where possible, the Real-Time Workshop software resolves violations of these requirements automatically, but most cases require changes to the parameters in some or all models.
For general information about setting configuration parameters for code generation, see Adjusting Simulation Configuration Parameters for Code Generation.
Configuration Requirements for Model Referencing with All System Targets
| Dialog Box Pane | Option | Requirement | |
|---|---|---|---|
| Solver | Start time | Some system targets require the start time of all models to be zero. | |
Hardware Implementation | Emulation hardware options | All values must be the same for top and referenced models. | |
Real-Time Workshop | System target file | Must be the same for top and referenced models. | |
| Language | Must be the same for top and referenced models. | ||
Generate code only | Must be the same for top and referenced models. | ||
Symbols | Maximum identifier length | Cannot be longer for a referenced model than for its parent model. | |
Interface | Target function library | Must be the same for top and referenced models. | |
Data exchange Interface | C-API | The C-API Signals and Parameters check boxes must be the same for top and referenced models. | |
| ASAP2 | Can be on or off in a top model, but must be off in a referenced model. If it is not, the Real-Time Workshop software temporarily sets it to off during code generation. | ||
Configuration Requirements for Model Referencing with ERT System Targets
| Dialog Box Pane | Option | Requirement | |
|---|---|---|---|
Real-Time Workshop | Ignore custom storage classes | Must be the same for top and referenced models. | |
Symbols | Global
variables Global types Subsystem methods Local temporary variables Constant macros | $R token must appear. | |
Signal naming | Must be the same for top and referenced models. | ||
| M-function | If specified, must be the same for top and referenced models. | ||
Parameter naming | Must be the same for top and referenced models. | ||
#define naming | Must be the same for top and referenced models. | ||
Interface | Support floating- point numbers | If off for top model, must be off for referenced models. | |
Support non-finite numbers | If off for top model, must be off for referenced models. | ||
Support complex numbers | If off for top model, must be off for referenced models. | ||
Terminate function required | Must be the same for top and referenced models. | ||
Suppress error status in real-time model | If on for top model, must be on for referenced models. | ||
Templates | Target operating system | Must be the same for top and referenced models. | |
Data Placement | Module Naming | Must be the same for top and referenced models. | |
| Module Name (if specified) | If set, must be the same for top and referenced models. | ||
Signal display level | Must be the same for top and referenced models. | ||
Parameter tune level | Must be the same for top and referenced models. | ||
Within a model that uses model referencing, there can be no collisions between the names of the constituent models. When you generate code from a model that uses model referencing, the Maximum identifier length parameter must be large enough to accommodate the root model name and the name mangling string (if needed). A code generation error occurs if Maximum identifier length is not large enough.
When a name conflict occurs between a symbol within the scope of a higher-level model and a symbol within the scope of a referenced model, the symbol from the referenced model is preserved. Name mangling is performed on the symbol from the higher-level model.
Embedded Coder Naming Requirements. The Real-Time Workshop® Embedded Coder™ product provides a Symbol format field that lets you control the formatting of generated symbols in much greater detail. When generating code with an ERT target from a model that uses model referencing:
The $R token must be included in the Identifier format control parameter specifications (in addition to the $M token).
The Maximum identifier length must be large enough to accommodate full expansions of the $R and $M tokens.
See Real-Time Workshop Pane: Symbols and Code Generation Options and Optimizations for more information.
A custom target must meet various requirements in order to support model referencing. See Supporting Model Referencing for details.
Models containing Model blocks can use signals of storage class Auto without restriction. However, when you declare signals to be global, you must be aware of how the signal data will be handled.
A global signal is a signal with a storage class other than Auto:
ExportedGlobal
ImportedExtern
ImportedExternPointer
Custom
The above are distinct from SimulinkGlobal signals, which are treated as test points with Auto storage class.
Global signals are declared, defined, and used as follows:
An extern declaration is generated by all models that use any given global signal.
As a result, if a signal crosses a Model block boundary, the top model and the referenced model both generate extern declarations for the signal.
For any exported signal, the top mode is responsible for defining (allocating memory for) the signal, whether or not the top model itself uses the signal.
All global signals used by a referenced model are accessed directly (as global memory). They are not passed as arguments to the functions that are generated for the referenced models.
Custom storage classes also follow the above rules. However, certain custom storage classes are not currently supported for use with model reference. See Custom Storage Class Limitations for details.
All storage classes are supported for both simulation and code generation, and all except Auto are tunable. The supported storage classes thus include
SimulinkGlobal
ExportedGlobal
ImportedExtern
ImportedExternPointer
Custom
Note the following restrictions on parameters in referenced models:
Tunable parameters are not supported for noninlined S-functions.
Tunable parameters set using the Model Parameter Configuration dialog box are ignored.
Note the following considerations concerning how global tunable parameters are declared, defined, and used in code generated for targets:
A global tunable parameter is a parameter in the base workspace with a storage class other than Auto.
An extern declaration is generated by all models that use any given parameter.
If a parameter is exported, the top model is responsible for defining (allocating memory for) the parameter (whether it uses the parameter or not).
All global parameters are accessed directly (as global memory). They are not passed as arguments to any of the functions that are generated for any of the referenced models.
Symbols for SimulinkGlobal parameters in referenced models are generated using unstructured variables (rtP_xxx) instead of being written into the model_P structure. This is so that each referenced model can be compiled independently.
Certain custom storage classes for parameters are not currently supported for model reference. See Custom Storage Class Limitations for details.
Parameters used as Model block arguments must be defined in the referenced model's workspace. See Parameterizing Model References in the Simulink documentation for specific details.
Within a parent model, the name and storage class for a signal entering or leaving a Model block might not match those of the signal attached to the root inport or outport within that referenced model. Because referenced models are compiled independently without regard to any parent model, they cannot adapt to all possible variations in how parent models label and store signals.
The Real-Time Workshop software accepts all cases where input and output signals in a referenced model have Auto storage class. When such signals are test pointed or are global, as described above, certain restrictions apply. The following table describes how mismatches in signal labels and storage classes between parent and referenced models are handled:
Relationships of Signals and Storage Classes Between Parent and Referenced Models
Referenced Model | Parent Model | Signal Passing Method | Signal Mismatch Checking |
|---|---|---|---|
Auto | Any | Function argument | None |
SimulinkGlobal or resolved to Signal Object | Any | Function argument | Label Mismatch Diagnostic (none / warning / error) |
Global | Auto or SimulinkGlobal | Global variable | Label Mismatch Diagnostic (none / warning / error) |
Global | Global | Global variable | Labels and storage classes must be identical (else error) |
To summarize, the following signal resolution rules apply to code generation:
If the storage class of a root input or output signal in a referenced model is Auto (or is SimulinkGlobal), the signal is passed as a function argument.
When such a signal is SimulinkGlobal or resolves to a Simulink.Signal object, the Signal Mismatch diagnostic is applied.
If a root input or output signal in a referenced model is global, it is communicated by using direct memory access (global variable). In addition,
If the corresponding signal in the parent model is also global, the names and storage classes must match exactly.
If the corresponding signal in the parent model is not global, the Signal Mismatch diagnostic is applied.
You can set the Signal Mismatch diagnostic to error, warning, or none in the Configuration Parameters > Diagnostics > Connectivity dialog.
See Inheriting Sample Times in the Simulink documentation for information about Model block sample time inheritance. In generated code, you can control inheriting sample time by using ssSetModelReferenceSampleTimeInheritanceRule in different ways:
An S-function that precludes inheritance: If the sample time is used in the S-function's run-time algorithm, then the S-function precludes a model from inheriting a sample time. For example, consider the following mdlOutputs code:
static void mdlOutputs(SimStruct *S, int_T tid)
{
const real_T *u = (const real_T*)
ssGetInputPortSignal(S,0);
real_T *y = ssGetOutputPortSignal(S,0);
y[0] = ssGetSampleTime(S,tid) * u[0];
}
This mdlOutputs code uses the sample time in its algorithm, and the S-function therefore should specify
ssSetModelReferenceSampleTimeInheritanceRule (S, DISALLOW_SAMPLE_TIME_INHERITANCE);
An S-function that does not preclude Inheritance: If the sample time is only used for determining whether the S-function has a sample hit, then it does not preclude the model from inheriting a sample time. For example, consider the mdlOutputs code from the S-function demo sfun_multirate.c:
static void mdlOutputs(SimStruct *S, int_T tid)
{
InputRealPtrsType enablePtrs;
int *enabled = ssGetIWork(S);
if (ssGetInputPortSampleTime
(S,ENABLE_IPORT)==CONTINUOUS_SAMPLE_TIME &&
ssGetInputPortOffsetTime(S,ENABLE_IPORT)==0.0) {
if (ssIsMajorTimeStep(S) &&
ssIsContinuousTask(S,tid)) {
enablePtrs =
ssGetInputPortRealSignalPtrs(S,ENABLE_IPORT);
*enabled = (*enablePtrs[0] > 0.0);
}
} else {
int enableTid =
ssGetInputPortSampleTimeIndex(S,ENABLE_IPORT);
if (ssIsSampleHit(S, enableTid, tid)) {
enablePtrs =
ssGetInputPortRealSignalPtrs(S,ENABLE_IPORT);
*enabled = (*enablePtrs[0] > 0.0);
}
}
if (*enabled) {
InputRealPtrsType uPtrs =
ssGetInputPortRealSignalPtrs(S,SIGNAL_IPORT);
real_T signal = *uPtrs[0];
int i;
for (i = 0; i < NOUTPUTS; i++) {
if (ssIsSampleHit(S,
ssGetOutputPortSampleTimeIndex(S,i), tid)) {
real_T *y = ssGetOutputPortRealSignal(S,i);
*y = signal;
}
}
}
} /* end mdlOutputs */
The above code uses the sample times of the block, but only for determining whether there is a hit. Therefore, this S-function should set
ssSetModelReferenceSampleTimeInheritanceRule (S, USE_DEFAULT_FOR_DISCRETE_INHERITANCE);
Models that employ model referencing might require special treatment when generating and using reusable code. The following sections identify general restrictions and discuss how reusable functions with inputs or outputs connected to a referenced model's root Inport or Outport blocks can affect code reuse.
You can generate code for subsystems that contain referenced models using the same procedures and options described in Nonvirtual Subsystem Code Generation. However, the following restrictions apply to such builds:
ERT S-functions do not support subsystems that contain a continuous sample time.
The Real-Time Workshop S-function target is not supported.
The Tunable parameters table (set by using the Model Parameter Configuration dialog box) is ignored; to make parameters tunable, you must define them as Simulink parameter objects in the base workspace.
All other parameters are inlined into the generated code and S-function.
Note You can generate subsystem code using any target configuration available in the System Target File Browser. However, if the S-function target is selected, Build Subsystem behaves identically to Generate S-function. (See Automated S-Function Generation.) |
Reusable functions with inputs or outputs connected to a referenced model's root Inport or Outport block can affect code reuse. This means that code for certain atomic subsystems cannot be reused in a model reference context the same way it is reused in a standalone model.
For example, suppose you create the following subsystem and make the following changes to the subsystem's block parameters:
Select Treat as an atomic unit
Set Real-Time Workshop system code to Reusable function

Suppose you then create the following model, which includes three instances of the preceding subsystem.

With the Inline parameters option enabled in this stand-alone model, the Real-Time Workshop code generator can optimize the code by generating a single copy of the function for the reused subsystem, as shown below.
void reuse_subsys1_Subsystem1(
real_T rtu_0,
rtB_reuse_subsys1_Subsystem1 *localB)
{
/* Gain: '<S1>/Gain' */
localB->Gain_k = rtu_0 * 3.0;
}
When generated as code for a Model block (into an slprj project directory), the subsystems have three different function signatures:
/* Output and update for atomic system: '<Root>/Subsystem1' */
void reuse_subsys1_Subsystem1(const real_T *rtu_0,
rtB_reuse_subsys1_Subsystem1
*localB)
{
/* Gain: '<S1>/Gain' */
localB->Gain_w = (*rtu_0) * 3.0;
}
/* Output and update for atomic system: '<Root>/Subsystem2' */
void reuse_subsys1_Subsystem2(real_T rtu_In1,
rtB_reuse_subsys1_Subsystem2
*localB)
{
/* Gain: '<S2>/Gain' */
localB->Gain_y = rtu_In1 * 3.0;
}
/* Output and update for atomic system: '<Root>/Subsystem3' */
void reuse_subsys1_Subsystem3(real_T rtu_In1, real_T *rty_0)
{
/* Gain: '<S3>/Gain' */
(*rty_0) = rtu_In1 * 3.0;
}
One way to make all the function signatures the same — and therefore assure code reuse — is to insert Signal Conversion blocks. Place one between the Inport and Subsystem1 and another between Subsystem3 and the Outport of the referenced model.

The result is a single reusable function:
void reuse_subsys2_Subsystem1(real_T rtu_In1,
rtB_reuse_subsys2_Subsystem1 *localB)
{
/* Gain: '<S1>/Gain' */
localB->Gain_g = rtu_In1 * 3.0;
}
You can achieve the same result (reusable code) with only one Signal Conversion block. You can omit the Signal Conversion block connected to the Inport block if you select the Pass scalar root inputs by value check box at the bottom of the Model Referencing pane of the Configuration Parameters dialog box. When you do this, you still need to insert a Signal Conversion block before the Outport block.
You can control the library file suffix, including the file type extension, that the Real-Time Workshop code generator uses to name generated model reference libraries by specifying the string for the suffix with the model configuration parameter TargetLibSuffix. The string must include a period (.). If you do not set this parameter,
| On a... | The Real-Time Workshop Software Names the Libraries... |
|---|---|
| Microsoft®Windows® system | model_rtwlib.lib |
| The Open Group UNIX® system | model_rtwlib.a |
The following Real-Time Workshop limitations apply to model referencing. In addition to these limitations, a model reference hierarchy used for code generation must satisfy:
The Simulink requirements listed in:
The Simulink limitations listed in Simulink® Model Referencing Limitations.
The Real-Time Workshop requirements applicable to the code generation target, as listed in Configuration Parameter Requirements.
The Real-Time Workshop code generator ignores custom code settings in the Configuration Parameter dialog box and custom code blocks when generating code for a referenced model.
Some restrictions exist on grouped custom storage classes in referenced models. See Custom Storage Class Limitations for details.
Referenced models do not support custom storage classes if the parent model has inline parameters off.
This release does not include Stateflow® target custom code in simulation targets generated for referenced models.
Data type replacement is not supported for simulation target code generation for referenced models.
Simulation targets do not include Stateflow target custom code.
To Workspace blocks, Scope blocks, and all types of runtime display, such as the display of port values and signal values, are ignored when the Real-Time Workshop software generates code for a referenced model. The resulting code is the same as if the constructs did not exist.
Code generated for referenced models cannot log data to MAT-files. If data logging is enabled for a referenced model, the Real-Time Workshop software disables the option before code generation and re-enables it afterwards.
If a referenced model used for code generation has any of the following properties, the model must specify Configuration Parameters > Model Referencing > Total number of instances allowed per top model as One, and no other instances of the model can exist in the hierarchy. If the parameter is not set correctly, or more than one instance of the model exists in the hierarchy, an error occurs. The properties are:
The model references another model which has been set to single instance
The model contains a state or signal with non-auto storage class
The model uses any of the following Stateflow constructs:
Machine-parented data
Machine-parented events
Stateflow graphical functions
The model contains a subsystem that is marked as function
The model contains an S-function that is:
Inlined but has not set the option SS_OPTION_WORKS_WITH_CODE_REUSE
Not inlined
The model contains a function-call subsystem that:
Has been forced by the Simulink engine to be a function
Is called by a wide signal
If a referenced model contains an S-function that should be inlined using a Target Language Compiler file, the S-function must use the ssSetOptions macro to set the SS_OPTION_USE_TLC_WITH_ACCELERATOR option in its mdlInitializeSizes method. The simulation target will not inline the S-function unless this flag is set.
The Real-Time Workshop software cannot generate code for a referenced model that includes noninlined S-functions.
A referenced model cannot use noninlined S-functions generated by the Real-Time Workshop software.
The Real-Time Workshop S-function target does not support model referencing.
Simulink tools that require access to a model's internal data or configuration (including the Model Coverage tool, the Simulink® Report Generator™ product, the Simulink debugger, and the Simulink profiler) have no effect on code generated by the Real-Time Workshop software for a referenced model, or on the execution of that code. Specifications made and actions taken by such tools are ignored and effectively do not exist.
If a subsystem contains Model blocks, you cannot build a subsystem module by right-clicking the subsystem (or by using Tools > Real-Time Workshop > Build subsystem) unless the model is configured to use an ERT target .
If you generate code for an atomic subsystem as a reusable function, inputs or outputs that connect the subsystem to a referenced model can affect code reuse, as described in Reusable Code and Referenced Models.
Real-Time Workshop grt_malloc targets do not support model reference.
The Real-Time Workshop S-function target does not support model referencing.
Errors or unexpected behavior can occur if a Model block is part of a cycle, the Model block is a direct feedthrough block, and an algebraic loop results. See Model Blocks and Direct Feedthrough for details.
The External mode option is not supported. If it is enabled, it is ignored during code generation.
![]() | Generating Code and Executables from Subsystems | Sharing Utility Functions | ![]() |
| © 1984-2008- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |