Configuring a Model

Selecting an ERT Target

The Browse button in the Target Selection subpane of the Real-Time Workshop > General pane lets you select an ERT target with the System Target File Browser. See Choosing and Configuring Your Target in the Real-Time Workshop® documentation for a general discussion of target selection.

To make it easier for you to generate code that is optimized for your target hardware, the code generator provides three variants of the ERT target that

The discussion throughout this chapter assumes use of the default ERT target.

These targets are based on a common system target file, ert.tlc. They are displayed in the System Target File Browser as shown in the figure below.

The optimized ERT target variants are discussed in detail in Generating Efficient Code with Optimized ERT Targets.

You can implement a custom auto-configuring target, using the same mechanism used by the optimized ERT target variants. Auto-Configuring Models for Code Generation discusses the auto-configuration mechanism and utilities used by the optimized ERT target variants.

You can use the ert_shrlib.tlc target to generate a host-based shared library from your Simulink® model. Selecting this target allows you to generate a shared library version of your model code that is appropriate for your host platform, either a Microsoft® Windows® dynamic link library (.dll) file or a UNIX®[1] shared object (.so) file. This feature can be used to package your source code securely for easy distribution and shared use. For more information, see Creating and Using Host-Based Shared Libraries.

Generating a Report that Includes Hyperlinks for Tracing Code to Model Blocks

Real-Time Workshop® Embedded Coder™ software extends the HTML code generation report that gets generated when you select the Create code generation report parameter. When you select this parameter for an ERT target, the parameters Code-to-model and Model-to-code appear. If you select these additional parameters, the HTML report includes hyperlinks from the code to the generating blocks in the model and right-clicking on the blocks in the model brings you to the code for that block. You can use these links to verify traceability of the generated code to the model.

For very large models (containing over 1000 blocks) generation of the hyperlinks can be time consuming. Therefore, if you do not have a need for traceability or after verifying the traceability of you generated code, consider disabling the parameter to speed up code generation.

For more information, see Code-to-model and Model-to-code in the Real-Time Workshop reference documentation.

Customizing Comments in Generated Code

You can customize the comments in the generated code for ERT targets by setting or clearing several parameters on the Real-Time Workshop > Comments pane. These options let you enable or suppress generation of descriptive information in comments for blocks and other objects in the model.

To...Select...
Include the text specified in the Description field of a block's Block Properties dialog box as comments in the code generated for each blockSimulink block descriptions.
Add a comment that includes the blockname at the start of the code for each blockSimulink block descriptions
Include the text specified in the Description field of a Simulink data object (such as a signal, parameter, data type, or bus) in the Simulink Model Explorer as comments in the code generated for each objectSimulink data object descriptions.
Include comments just above signals and parameter identifiers in the generated code as specified in an M-code or TLC function. Custom comments (MPT objects only).
Include the text specified in the Description field of the Properties dialog box for a Stateflow® object as comments just above the code generated for each objectStateflow object descriptions.
Include requirements assigned to Simulink blocks in the generated code comments (for more information, see Including Requirements with Generated Code in the Simulink® Verification and Validation™ documentation)Requirements in block comments.

When you select Simulink block descriptions,

For more information, see Real-Time Workshop Pane: Comments in the Real-Time Workshop reference documentation.

Customizing Generated Identifiers

Several parameters are available for customizing generated symbols.

To...Specify...
Define a macro string that specifies whether, and in what order, certain substrings are included within generated identifiers for global variables, global types, field names of global types, subsystem methods, local temporary variables, local block output variables, and constant macros The macro string with the Identifier format control parameter (for details on how to specify formats, see Specifying Identifier Formats and for limitations, see Identifier Format Control Parameters Limitations).
Specify the minimum number of characters the code generator uses for mangled symbolsSpecify an integer value for the Minimum mangle length (for details, see Name Mangling).
Specify the maximum number of characters the code generator can use for function, typedef, and variable names (default 31) Specify an integer value for the Maximum identifier length. If you expect your model to generate lengthy identifiers (due to use of long signal or parameter names, for example), or you find that identifiers are being mangled more than expected, you should increase the value of this parameter.
Control whether scalar inlined parameter values are expressed in generated code as literal values or macros

The value Literals or Macros for the Generate scalar inlined parameters as parameter

.
  • Literals: Parameters are expressed as numeric constants and takes effect if Inline parameters is selected.

  • Macros: Parameters are expressed as variables (with #define macros). This setting makes code more readable.

For more information, see Real-Time Workshop Pane: Symbols in the Real-Time Workshop reference documentation.

Configuring Symbols

Specifying Simulink® Data Object Naming Rules

To Define Rules that Change the Names of a Model's...Specify a Naming Rule with the ...
SignalsSignal naming parameter
ParametersParameter naming parameter
Parameters that have a storage class of Define#define naming parameter

For more information on these parameters, see Specifying Simulink® Data Object Naming Rules in the Real-Time Workshop Embedded Coder Module Packaging Features document.

Specifying Identifier Formats

The Identifier format control parameters let you customize generated identifiers by entering a macro string that specifies whether, and in what order, certain substrings are included within generated identifiers. For example, you can specify that the root model name be inserted into each identifier.

The macro string can include

The build process generates each identifier by expanding tokens (in the order listed in Identifier Format Tokens) and inserting the resultant strings into the identifier. Character strings between tokens are simply inserted directly into the identifier. Contiguous token expansions are separated by the underscore (_) character.

Identifier Format Tokens

TokenDescription
$M

Insert name mangling string if required to avoid naming collisions (see Name Mangling). Note: This token is required.

$F

Insert method name (for example, _Update for update method). This token is available only for subsystem methods.

$N

Insert name of object (block, signal or signal object, state, parameter or parameter object) for which identifier is being generated.

$R

Insert root model name into identifier, replacing any unsupported characters with the underscore (_) character. Note that when using model referencing, this token is required in addition to $M (see Model Referencing Considerations).

Note: This token replaces the Prefix model name to global identifiers option used in previous releases.

$H

Insert tag indicating system hierarchy level. For root-level blocks, the tag is the string root_. For blocks at the subsystem level, the tag is of the form sN_, where N is a unique system number assigned by the Simulink software. This token is available only for subsystem methods and field names of global types.

Note: This token replaces the Include System Hierarchy Number in Identifiers option used in previous releases.

$A

Insert data type acronym (for example, i32 for long integers) to signal and work vector identifiers. This token is available only for local block output variables and field names of global types.

Note: This token replaces the Include data type acronym in identifier option used in previous releases.

Identifier Format Control Parameter Values lists the default macro string, the supported tokens, and the applicable restrictions for each Identifier format control parameter.

Identifier Format Control Parameter Values

ParameterDefault ValueSupported TokensRestrictions
Global variables$R$N$M$R, $N, $M$F, $H, and $A are disallowed.
Global types$N$R$M$N, $R, $M$F, $H, and $A are disallowed.
Field name of global types$N$M$N, $M, $H, $A$R and $F are disallowed.
Subsystem methods$R$N$M$F$R, $N, $M, $F, $H$F and $H are empty for Stateflow functions; $A is disallowed.
Local temporary variables$N$M$N, $M, $R$F, $H, and $A are disallowed.
Local block output variablesrtb_$N$M$N, $M, $A$R, $F, and $H are disallowed.
Constant macros$R$N$M$R, $N, $M$F, $H, and $A are disallowed.

Non-ERT based targets (such as the GRT target) implicitly use a default $R$N$M specification. This specifies identifiers consisting of the root model name, followed by the name of the generating object (signal, parameter, state, and so on), followed by a name mangling string (see Name Mangling).

For limitations that apply to Identifier format control parameters, see Identifier Format Control Parameters Limitations.

Name Mangling

In identifier generation, a circumstance that would cause generation of two or more identical identifiers is called a name collision. Name collisions are never permissible. When a potential name collision exists, unique name mangling strings are generated and inserted into each of the potentially conflicting identifiers. Each name mangling string is guaranteed to be unique for each generated identifier.

The position of the $M token in the Identifier format control parameter specification determines the position of the name mangling string in the generated identifiers. For example, if the specification $R$N$M is used, the name mangling string is appended (if required) to the end of the identifier.

The Minimum mangle length parameter specifies the minimum number of characters used when a name mangling string is generated. The default is 1 character. As described below, the actual length of the generated string may be longer than this minimum.

Traceability

An important aspect of model based design is the ability to generate identifiers that can easily be traced back to the corresponding entities within the model. To ensure traceability, it is important to make sure that incremental revisions to a model have minimal impact on the identifier names that appear in generated code. There are two ways of achieving this:

  1. Choose unique names for Simulink objects (blocks, signals, states, and so on) as much as possible.

  2. Make use of name mangling when conflicts cannot be avoided.

When conflicts cannot be avoided (as may be the case in models that use libraries or model reference), name mangling ensures traceability. The position of the name mangling string is specified by the placement of the $M token in the Identifier format control parameter specification. Mangle characters consist of lower case characters (a-z) and numerics (0-9), which are chosen with a checksum that is unique to each object. How Name Mangling Strings Are Computed describes how this checksum is computed for different types of objects.

How Name Mangling Strings Are Computed

Object TypeSource of Mangling String

Block diagram

Name of block diagram

Simulink block

Full path name of block

Simulink parameter

Full name of parameter owner (that is, model or block) and parameter name

Simulink signal

Signal name, full name of source block, and port number

Stateflow objects

Complete path to Stateflow block and Stateflow computed name (unique within chart)

The length of the name mangling string is specified by the Minimum mangle length parameter. The default value is 1, but this automatically increases during code generation as a function of the number of collisions.

To minimize disturbance to the generated code during development, specify a larger Minimum mangle length. A Minimum mangle length of 4 is a conservative and safe value. A value of 4 allows for over 1.5 million collisions for a particular identifier before the mangle length is increased.

Minimizing Name Mangling

Note that the length of generated identifiers is limited by the Maximum identifier length parameter. When a name collision exists, the $M token is always expanded to the minimum number of characters required to avoid the collision. Other tokens and character strings are expanded in the order listed in Identifier Format Tokens. If the Maximum identifier length is not large enough to accommodate full expansions of the other tokens, partial expansions are used. To avoid this outcome, it is good practice to

Model Referencing Considerations

Within a model that uses model referencing, there can be no collisions between the names of the constituent models. When generating code from a model that uses model referencing:

When a name conflict occurs between an identifier within the scope of a higher-level model and an identifier within the scope of a referenced model, the identifier from the referenced model is preserved. Name mangling is performed on the identifier from the higher-level model.

Exceptions to Identifier Formatting Conventions

There are some exceptions to the identifier formatting conventions described above:

Identifier Format Control Parameters Limitations

The following limitations apply to the Identifier format control parameters:

Configuring Model Interfaces

In addition to the interface parameters available for GRT targets, you can configure the following for ERT targets:

Configuring Support for Numeric Data

By default, ERT targets support code generation for integer, floating-point, non-finite, and complex numbers.

To Generate Code that Supports...Do...
Integer data onlyDeselect Support floating-point numbers. If any noninteger data or expressions are encountered during code generation, an error message reports the offending blocks and parameters.
Floating-point data Select Support floating-point numbers.
Non-finite values (for example, NaN, Inf)Select Support floating-point numbers and Support non-finite numbers .
Complex data Select Support complex numbers .

For more information, see Real-Time Workshop Pane: Interface in the Real-Time Workshop reference documentation.

Configuring Support for Time Values

Certain blocks require the value of absolute time (that is, the time from the start of program execution to the present time) , elapsed time (for example, the time elapsed between two trigger events), or continuous time. Depending on the blocks used, you might need to adjust the configuration settings for supported time values.

To...Select...
Generate code that creates and maintains integer counters for blocks that use absolute or elapsed time values (default)Support absolute time. For further information on the allocation and operation of absolute and elapsed timers, see the Timing Services chapter of the Real-Time Workshop documentation. If you do not select this parameter and the model includes block that use absolute or elapsed time values, the build process generates an error.
Generate code for blocks that rely on continuous timeSupport continuous time. If you do not select this parameter and the model includes continuous-time blocks, the build process generates an error.

For more information, see Real-Time Workshop Pane: Interface in the Real-Time Workshop reference documentation.

Configuring Support for Non-Inlined S-Functions

To generate code for non-inlined S-functions in a model, select Support non-inlined S-functions. The generation of non-inlined S-functions requires floating-point and non-finite numbers. Thus, when you select Support non-inlined S-functions, the ERT target automatically selects Support floating-point numbers and Support non-finite numbers.

When you select Support non-finite numbers, the build process generates an error if the model includes a C-MEX S-function that does not have a corresponding TLC implementation (for inlining code generation).

Note that inlining S-functions is highly advantageous in production code generation, for example in implementing device drivers. To enforce the use of inlined S-functions for code generation, deselect Support non-inlined S-functions.

For more information, see Real-Time Workshop Pane: Interface in the Real-Time Workshop reference documentation.

Configuring Model Function Generation and Argument Passing

For ERT targets, you can configure how a model's functions are generated and how arguments are passed to the functions.

To...Do...
Generate model function calls that are compatible with the main program module of the GRT target (grt_main.c or .cpp)Select GRT compatible call interface and MAT-file logging . In addition, deselect Suppress error status in real-time model data structure. GRT compatible call interface provides a quick way to use ERT target features with a GRT-based custom target by generating wrapper function calls that interface to the ERT target's Embedded-C formatted code.
Reduce overhead and use more local variables by combining the output and update functions in a single model_step functionSelect Single output/update function

Errors or unexpected behavior can occur if a Model block is part of a cycle and Single output/update function is enabled (the default). See Model Blocks and Direct Feedthrough for details.

Generate a model_terminate function for a model not designed to run indefinitelySelect Terminate function required. For more information, see the description of model_terminate.
Generate reusable, reentrant code from a model or subsystem Select Generate reusable code. See Configuring a Model for Code Reuse for details.
Statically allocate model data structures and access them directly in the model codeDeselect Generate reusable code. The generated code is not reusable or reentrant. See Model Entry Points for information on the calling interface generated for model functions in this case.
Suppress the generation of an error status field in the real-time model data structure, rtModel, for example, if you do not need to log or monitor error messages

Select Suppress error status in real-time model data structure. Selecting this parameter can also cause the rtModel structure to be omitted completely from the generated code.

When generating code for multiple integrated models, set this parameter the same for all of the models. Otherwise, the integrated application might exhibit unexpected behavior. For example, if you select the option in one model but not in another, the error status might not be registered by the integrated application.

Do not select this parameter if you select the MAT-file logging option. The two options are incompatible.

Launch the Model Interface dialog box (see Model Interface Dialog Box) preview and modify the model's model_step function prototype Click Configure Step Function. Based on the Function specification value you select for your model_step function (supported values include Default model-step function and Model specific C prototype), you can preview and modify the function prototype. Once you validate and apply your changes, you can generate code based on your function prototype modifications. For more information about using the Configure Step Function button and the Model Interface dialog box, see Controlling model_step Function Prototypes.

For more information, see Real-Time Workshop Pane: Interface in the Real-Time Workshop reference documentation.

Configuring a Model for Code Reuse

For ERT targets, you can configure how a model reuses code using the Generate reusable code parameter.

Pass root-level I/O as provides options that control how model inputs and outputs at the root level of the model are passed to the model_step function.

To...Select...
Pass each root-level model input and output argument to the model_step function individually (the default)Generate reusable code and Pass root-level I/O as > Individual arguments.
Pack root-level input arguments and root-level output arguments into separate structures that are then passed to the model_step functionGenerate reusable code and Pass root-level I/O as > Structure reference

In some cases, selecting Generate reusable code can generate code that compiles but is not reentrant. For example, if any signal, DWork structure, or parameter data has a storage class other than Auto, global data structures are generated. To handle such cases, use the Reusable code error diagnostic parameter to choose the severity levels for diagnostics

In some cases, the Real-Time Workshop Embedded Coder software is unable to generate valid and compilable code. For example, if the model contains any of the following, the code generated would be invalid.

In these cases, the build terminates after reporting the problem.

For more information, see Real-Time Workshop Pane: Interface in the Real-Time Workshop reference documentation.

Controlling Code Style

You can control the following style aspects in generated code:

For example, C code contains some syntactically required parentheses, and can contain additional parentheses that change semantics by overriding default operator precedence. C code can also contain optional parentheses that have no functional significance, but serve only to increase the readability of the code. Optional C parentheses vary between two stylistic extremes:

Understanding code with minimum parentheses can require correctly applying nonobvious precedence rules, but maximum parentheses can hinder code reading by belaboring obvious precedence rules. Various parenthesization standards exist that specify one or the other extreme, or define an intermediate style that can be useful to human code readers.

You control the code style options by setting parameters on the Real-Time Workshop > Code Style pane. For details on the parameters, see Real-Time Workshop Pane: Code Style in the Real-Time Workshop Embedded Coder reference documentation.

Configuring Templates for Customizing Code

Code and data templates provide a way to customize generated code.

To...Enter or Select...
Specify a template that defines the top-level organization and formatting of generated source code (.c or .cpp) files Enter a code generation template (CGT) file for the Source file (*.c) template parameter. .
Specify a template that defines the top-level organization and formatting of generated header (.h) files Enter a CGT file for the Header file (*.h) template parameter. This can be the same template file that you specify for Source file (.c) template, in which case identical banners are generated in source and header files. The default template is matlabroot
/toolbox/rtw/targets/ecoder/ert_code_template.cgt
.
Specify a template that organizes generated code into sections (such as includes, typedefs, functions, and more)Enter a custom file processing (CFP) template file for the File customization template parameter. . A CFP template can emit code, directives, or comments into each section as required. See Custom File Processing for detailed information.
Generate a model-specific example main program moduleSelect Generate an example main program. See Generating the Main Program Module for more information.

Template files that you specify must be located on the MATLAB® path.

For more detail, see the Module Packaging Features document. See also Generating Custom File Banners for a simple example of how a code template can be applied to generate customized comment sections in generated code files.

Configuring the Placement of Data in Code

To...Select or Enter...
Specify whether data is to be defined in the generated source file or in a single separate header fileSelect Auto, Data defined in source file, or Data defined in single separate source file for the Data definition parameter.
Specify whether data is to be declared in the generated source file or in a single separate header fileSelect Auto, Data defined in source file, or Data defined in single separate source file for the Data declaration parameter.
Specify the #include file delimiter to be used in generated files that contain the #include preprocessor directive for mpt data objectsSelect Auto, Data defined in source file, or Data defined in single separate source file for the #include file delimiter parameter.
Name the generated module using the same name as the model or a user-specified nameSelect Not specified, Same as model, or User specified for the Module naming parameter.
Control whether signal data objects are to be declared as global data in the generated codeEnter an integer value for the Signal display level parameter.
Declare a parameter data object as tunable global data in the generated codeEnter an integer value for the Parameter tune level parameter.

For details data placement, see the Module Packaging Features document.

Configuring Replacement Data Types

You can replace built-in data type names with user-defined replacement data type names in the generated code for a model.

To configure replacement data types,

  1. Click Replace data type names in the generated code. A Data type names table appears. The table lists each Simulink built-in data type name with its corresponding Real-Time Workshop data type name.

  2. Selectively fill in fields in the third column with your replacement data types. Each replacement data type should be the name of a Simulink.AliasType object that exists in the base workspace. Replacements may be specified or not for each individual built-in type.

    For each replacement data type you enter, the BaseType property of the associated Simulink.AliasType object must be consistent with the built-in data type it replaces.

    An error occurs if a replacement data type specification is inconsistent. For more information, see Replacing Built-In Data Type Names in Generated Code in the Module Packaging Features document.

Configuring Memory Sections

You can configure a model such that the generated code includes comments and pragmas for

To...Select...
Specify the package that contains memory sections that you want to applyThe name of a package for Package. Click Refresh package list to refresh the list of available packages in your configuration.
Apply memory sections to initialize/start and terminate functionsA value for Initialize/Terminate.
Apply memory sections to step, run-time initialization, derivative, enable, and disable functionsA value for Execution.
Apply memory sections to constant parameters, constant, block I/O, or zero representationA value for Constants.
Apply memory sections to root inputs or outputsA value for Inputs/Outputs.
Apply memory sections to block I/O, Dwork vectors, run-time models, zero-crossingsA value for Internal data.
Apply memory sections to parametersA value for Parameters.

The interface checks whether the specified package is on the MATLAB path and that the selected memory sections are in the package. The results of this validation appear in the field Validation results.

For details on using memory sections, see Memory Sections.

Configuring Optimizations

To...Select or Specify...
Control whether parameter data for reusable subsystems is generated in a separate header file for each subsystem or in a single parameter data structureSelect Hierarchical or NonHierarchical for Parameter structure.
Generate initialization code for root-level inports and outports with a value of zeroSelect Remove root level I/O zero initialization.
Generate additional code to set float and double storage explicitly to value 0.0Select Use memset to initialize floats and doubles to 0.0 When you set this parameter, the memset function clears internal storage (regardless of type) to the integer bit pattern 0 (that is, all bits are off). The additional code generated when the option is off, is slightly less efficient.

If the representation of floating-point zero used by your compiler and target CPU is identical to the integer bit pattern 0, you can gain efficiency by setting this parameter.

Suppress the generation of code that initializes internal work structures (for example, block states and block outputs) to zeroSelect Remove internal state zero initialization.
Generate run-time initialization code for a block that has states only if the block is in a system that can reset its states, such as an enabled subsystem Select Optimize initialization code for model reference This results in more efficient code, but requires that you not refer to the model from a Model block that resides in a system that resets its states. Such nesting results in an error. Turn this option off only if your application requires you refer to the model from Model blocks in systems that can reset their states.
Remove code that ensures that execution of the generated code produces the same results as simulation when out-of-range conversions occurSelect Remove code from floating-point to integer conversions that wraps out-of-range values. This reduces the size and increases the speed of the generated code at the cost of potentially producing results that do not match simulation in the case of out-of-range values.
Suppress generation of code that guards against fixed-point division by zeroSelect Remove code that protects against division arithmetic exceptions. When you select this parameter, simulation results and results from generated code may no longer be in bit-for-bit agreement.
To minimize the amount of memory allocated for absolute and elapsed time counters Specify an integer value for Application lifespan (days) For more information on the allocation and operation of absolute and elapsed timers, see Timing Services, Using Timers in Asynchronous Tasks, and Controlling Memory Allocation for Time Counters in the Real-Time Workshop documentation.


[1] UNIX is a registered trademark of The Open Group in the United States and other countries.

[2] ANSI is a registered trademark of the American National Standards Institute, Inc.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS