| Contents | Index |
You can customize the comments in the generated code for ERT targets by setting or clearing several parameters on the Code Generation > 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 block | Simulink block descriptions. |
| Add a comment that includes the block name at the start of the code for each block | Simulink 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 object | Simulink data object descriptions. |
| Include comments just above signals and parameter identifiers in the generated code as specified in the MATLAB 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 object | Stateflow object descriptions. |
| Include requirements assigned to Simulink blocks in the generated code comments (for more information, see Requirements Information in Generated Code in the Simulink Verification and Validation documentation) | Requirements in block comments. |
When you select Simulink block descriptions,
The description text for blocks and Stateflow objects and block names generated as comments can include international (non-US-ASCII) characters. (For details on international character support, see Support for International (Non-US-ASCII) Characters.)
The code generation software automatically inserts comments into the generated code for custom blocks. Therefore, it is not required to include block comments in the associated TLC file for a custom block.
Note If you have existing TLC files with manually inserted comments for block descriptions, the code generation process emits these comments instead of the automatically generated comments. Consider removing existing block comments from your TLC files. Manually inserted comments might be poorly formatted in the generated code and code-to-model traceability might not work. |
For virtual blocks or blocks that have been removed due to block reduction, no comments are generated.
For more information, see Code Generation Pane: Comments.
This procedure allows you to add a comment just above a signal or parameter's identifier in the generated code. This is accomplished using
A MATLAB or TLC function that you write and save in a .m or .tlc file
The Custom comments (MPT objects only) check box on the Comments pane of the Configuration Parameters dialog box
Selecting the .m or .tlc file in the Custom comments function field on the Comments pane of the Configuration Parameters dialog box.
You may include at least some or all of the property values for the data object. Each Simulink data object (signal or parameter) has properties, as described in Parameter and Signal Property Values. This example comment contains some of the property values for the data object MAP as specified on the Model Explorer:
/* DocUnits: PSI */ /* Owner: */ /* DefinitionFile: specialDef */ real_T MAP = 0.0;
You can type text in the Description field on the Model Explorer for a signal or parameter data object. If you do, and if you select the Simulink data object descriptions check box on the Comments pane of the Configuration Parameters dialog box, this text will appear beside the signal's or parameter's identifier in the generated code as a comment. This is true whether or not you select the Custom comments (MPT objects only) check box discussed in this procedure. For example, typing Manifold Absolute Pressure in the Description field for the data object MAP always will result in the following in the generated code:
real_T MAP = 0.0; /* Manifold Absolute Pressure */
To add a comment just above a signal or parameter's identifier in the generated code, do the following:
The signal or parameter MPT object must use a custom storage class. Open the MPT object properties dialog box and confirm that the Storage class is a custom storage class ((Custom) suffixed to its name). The default storage class for an MPT object is Global (Custom).
Write a MATLAB or TLC function that places comments in the generated files as desired. An example .m file named rtwdemo_comments_mptfun.m is provided in the matlab/toolbox/rtw/rtwdemos folder. This file contains instructions.
The MATLAB function must have three arguments that correspond to objectName, modelName, and request, respectively. The TLC function must have three arguments that correspond to objectName, modelName, and request, respectively. Note also, in the case of the TLC file, you can use the library function LibGetSLDataObjectInfo to get every property value of the data object.
Save the function as a .m file or a .tlc file with the desired filename and place it in any folder in the MATLAB path.
Click Comments under Code Generation on the left pane. The Comments pane appears on the right.
In the Custom comments function field, either type the filename of the .m file or .tlc file you created, or select this filename using the Browse button.
Open the generated files and inspect their content to check that the comments are what you want.
Introduction. The procedures in this section explain how to add a global comment to a Simulink model so that the comment text appears in the generated file or files where desired. This is accomplished by specifying a template symbol name with a Simulink DocBlock, a Simulink annotation, or a Stateflow note, or by using a sorted-notes capability that works with Simulink annotations or Stateflow notes (but not DocBlocks). For more information about template symbols, see Template Symbols and Rules.
Note Template symbol names Description and ModifiedHistory, referenced below, also are fields in the Model Properties dialog box. If you use one of these symbol names for global comment text, and its Model Properties field has text in it too, both will appear in the generated files. |
Use a Simulink DocBlock to Add a Comment.
With the model open, select Library Browser from the View menu.
Drag the DocBlock from Model-Wide Utilities in the Simulink library onto the model.
After double-clicking the DocBlock and typing the desired comment in the editor, save and close the editor. See DocBlock in the Simulink documentation for details.
Right-click the DocBlock and select Mask Parameters. The Block Parameters dialog box appears.
Type one of the following into the Code generation template symbol field, illustrated below, and then click OK: Abstract, Description, History, ModifiedHistory, or Notes. Template symbol names are case sensitive.

In the Block Properties dialog box, Block Annotation tab, select %<ECoderFlag> as shown in the figure below, and then click OK. The symbol name typed in the previous step now appears under the DocBlock on the model.

Save the model. After you generate code, the code generator places the comment in each generated file whose template has the symbol name you typed. The code generator places the comment in the generated file at the location that corresponds to where the symbol name is located in the template file.
To add one or more other comments to the generated files, repeat steps 1 through 7 as desired.
Use a Simulink Annotation to Add a Comment.
Double-click the unoccupied area on the model where you want to place the comment. See Annotating Diagrams in the Simulink documentation for details.
Note If you want the code generator to sort multiple comments for the Notes symbol name, replace the next step with Use Sorted Notes to Add Comments. |
Type <S:Symbol_name> followed by the comment, where Symbol_name is one of the following Documentation child : Abstract, Description, History, ModifiedHistory, or Notes. For example, type <S:Description>This is the description I want. Template symbol names are case sensitive. (The "S" before the colon indicates "symbol.")
Click outside the rectangle and save the model. After you generate code, the code generator places the comment in each generated file whose template has the symbol name you typed. The code generator places the comment in the generated file at the location that corresponds to where the symbol name is located in the template file.
To add one or more other comments to the generated files, repeat steps 1 through 3 as desired.
Use a Stateflow Note to Add a Comment.
Right-click the desired unoccupied area on the Stateflow chart where you want to place the comment. See Using Descriptive Comments in a Chart in the Stateflow documentation for details.
Select Add Note from the drop down menu.
Note If you want the code generator to sort multiple comments for the Notes symbol name, replace the next step with Use Sorted Notes to Add Comments. |
Type <S:Symbol_name> followed by the comment, where Symbol_name is one of the following Documentation child : Abstract, Description, History, ModifiedHistory, or Notes. For example, type <S:Description>This is the description I want. Template symbol names are case sensitive.
Click outside the note and save the model. After you generate code, the code generator places the comment in each generated file whose template has the symbol name you typed. The code generator places the comment in the generated file at the location that corresponds to where the symbol name is located in the template file.
To add one or more other comments to the generated files, repeat steps 1 through 4 as desired.
Use Sorted Notes to Add Comments. The sorted-notes capability allows you to add automatically sorted comments to the generated files. The code generator places these comments in each generated file at the location that corresponds to where the Notes symbol is located in the template file.
The sorting order the code generator uses is
Numbers before letters
Among numbers, 0 is first
Among letters, uppercase are before lowercase.
You can use sorted notes with a Simulink annotation or a Stateflow note, but not with a DocBlock:
In the Simulink annotation or the Stateflow note, type <S:NoteY> followed by the first comment, where Y is a number or letter.
Repeat for as many additional comments you want, except replace Y with a subsequent number or letter.
The figure below illustrates sorted notes on a model, and where the code generator places each in a generated file.

Here is the relevant fragment from the generated file for the above model:
** NOTES ** Note1: This is the first comment I want associated with the Notes symbol. Note2: This is the second comment I want under Notes. Noteb: This is the third comment. **
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, subsystem method arguments, 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 Specify Identifier Formats and for limitations, see Identifier Format Control Parameters Limitations). |
| Specify the minimum number of characters the code generator uses for mangled symbols | Specify 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 .
|
For more information, see Code Generation Pane: Symbols.
Specify Simulink Data Object Naming Rules.
| To Define Rules that Change the Names of a Model's... | Specify a Naming Rule with the ... |
|---|---|
| Signals | Signal naming parameter |
| Parameters | Parameter naming parameter |
| Parameters that have a storage class of Define | #define naming parameter |
For more information on these parameters, see Specify Simulink Data Object Naming Rules.
Specify 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
Tokens of the form $X, where X is a single character. Valid tokens are listed in Identifier Format Tokens. You can use or omit tokens as you want, with the exception of the $M token, which is required (see Name Mangling) and subject to the use and ordering restrictions noted in Identifier Format Control Parameter Values.
Any valid C or C++ language identifier characters (a-z, A-Z, _ , 0-9).
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
| Token | Description |
|---|---|
| $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. |
| $I | Insert u if the argument is an input or y if the argument is an output, (for example, rtu_ for an input argument and rty_ for an output argument). This token is available only for subsystem method arguments. |
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
| Parameter | Default Value | Supported Tokens | Restrictions |
|---|---|---|---|
| Global variables | $R$N$M | $R, $N, $M | $F, $H, $A, and $I are disallowed. |
| Global types | $N$R$M | $N, $R, $M | $F, $H, $A, and $I are disallowed. |
| Field name of global types | $N$M | $N, $M, $H, $A | $R, $F, and $I are disallowed. |
| Subsystem methods | $R$N$M$F | $R, $N, $M, $F, $H | $F and $H are empty for Stateflow functions; $A and $I are disallowed. |
| Subsystem method arguments | rtu_$N$M or rty_$N$M | $N, $M, $I | $R, $F, $H, and $A are disallowed. |
| Local temporary variables | $N$M | $N, $M, $R | $F, $H, $A, and $I are disallowed. |
| Local block output variables | rtb_$N$M | $N, $M, $A | $R, $F, $H, and $I are disallowed. |
| Constant macros | $R$N$M | $R, $N, $M | $F, $H, $A, and $I 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 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 maintain 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:
When conflicts cannot be avoided (as may be the case in models that use libraries or model reference), name mangling helps 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 alphanumeric characters that are unique to each object. How Name Mangling Strings Are Computed describes the checksum computed for mangling strings for different types of objects.
How Name Mangling Strings Are Computed
| Object Type | Source of Mangling String |
|---|---|
Block diagram | Name of block diagram |
Simulink block | Simulink Identifier (SID) |
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 value. A value of 4 allows for over 1.5 million collisions for a particular identifier before the mangle length is increased.
Minimize 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
Avoid name collisions in general. One way to do this is to avoid using default block names (for example, Gain1, Gain2...) when there are many blocks of the same type in the model.
Where possible, increase the Maximum identifier length to accommodate the length of the identifiers you expect to generate.
Set the Minimum mangle length parameter to reserve at least three characters for the name mangling string. The length of the name mangling string increases as the number of name collisions increases.
Note that an existing name mangling string increases (or decreases) in length if changes to model create more (or fewer) collisions. If the length of the name mangling string increases, additional characters are appended to the existing string. For example, 'xyz' might change to 'xyzQ'. In the inverse case (fewer collisions) 'xyz' would change to 'xy'.
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:
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. A code generation warning occurs if Maximum identifier length is not large enough.
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.
If your model contains two referenced models with the same input or output port names, and one of the referenced models contains an atomic subsystem with Function packaging set to Function, a name conflict might occur and the build process produces an error.
Exceptions to Identifier Formatting Conventions. There are some exceptions to the identifier formatting conventions described above:
Type name generation: The above name mangling conventions do not apply to type names (that is, typedef statements) generated for global data types. If the $R token is included in the Identifier format control parameter specification, the model name is included in the typedef. The Maximum identifier length parameter is not respected when generating type definitions.
Non-Auto storage classes: The Identifier format control parameter specification does not affect objects (such as signals and parameters) that have a storage class other than Auto (such as ImportedExtern or ExportedGlobal).
Identifier Format Control Parameters Limitations. The following limitations apply to the Identifier format control parameters:
The following autogenerated identifiers currently do not fully comply with the setting of the Maximum identifier length parameter on the Code Generation > Symbols pane of the Configuration Parameters dialog box.
Model methods
The applicable format string is $R$F, and the longest $F is _derivatives, which is 12 characters long. The model name can be up to 19 characters without exceeding the default Maximum identifier length of 31.
Local functions generated by S-functions or by add-on products such as DSP System Toolbox™ that rely on S-functions
Local variables generated by S-functions or by add-on products such as DSP System Toolbox that rely on S-functions
DWork identifiers generated by S-functions in referenced models
Fixed-point shared utility macros or shared utility functions
Simulink rtm macros
Most are within the default Maximum identifier length of 31, but some exceed the limit. Examples are RTMSpecAccsGetStopRequestedValStoredAsPtr, RTMSpecAccsGetErrorStatusPointer, and RTMSpecAccsGetErrorStatusPointerPointer.
Define protection guard macros
Header file guards, such as _RTW_HEADER_$(filename)_h_, which can exceed the default Maximum identifier length of 31 given a filename such as $R_private.h.
Include file guards, such as _$R_COMMON_INCLUDES_.
typedef guards, such as _CSCI_$R_CHARTSTRUCT_.
In some situations, the following identifiers potentially can conflict with others.
Model methods
Reentrant model function arguments
Local functions generated by S-functions or by add-on products such as DSP System Toolbox that rely on S-functions
Local variables generated by S-functions or by add-on products such as DSP System Toolbox that rely on S-functions
Fixed-point shared utility macros or shared utility functions
Include header guard macros
The following external identifiers that are unknown to the Simulink software might conflict with autogenerated identifiers.
Identifiers defined in custom code
Identifiers defined in custom header files
Identifiers introduced through a non-ANSI C standard library
Identifiers defined by custom TLC code
Identifiers generated for simulation targets may exceed the Maximum identifier length. Simulation targets include the model reference simulation target, the accelerated simulation target, the RSim target, and the S-function target.
You can control the following style aspects in generated code:
Level of parenthesization
Whether to preserve order of operands in expressions
Whether to preserve empty primary condition expressions in if statements
Whether to generate code for if-elseif-else decision logic as switch-case statements
Whether to include the extern keyword in function declarations
Whether to always generate default cases for switch-case statements in the code for Stateflow charts
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:
Include the minimum parentheses required by C syntax and any precedence overrides, so that C precedence rules specify all semantics unless overridden by parentheses.
Include the maximum parentheses that can exist without duplication, so that C precedence rules become irrelevant: parentheses alone completely specify all semantics.
Understanding code with minimum parentheses can require 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 Code Generation > Code Style pane. For details on the parameters, see Code Generation Pane: Code Style.
Customize generated code using code and data templates
| 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 template file can be the
same template file that you specify for Source file (.c)
template. If you use the same template file, source and
header files contain identical banners. 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. For more information, see Use Custom File Processing (CFP) Templates. |
| Generate a model-specific example main program module | Select Generate an example main program. For more information, see Generate a Standalone Program. |
This section describes Embedded Coder custom file processing (CFP) features. Custom file processing simplifies generation of custom source code. You can:
Generate any type of source (.c or .cpp) or header (.h) file. Using a custom file processing template (CFP template), you can control how code emits to the standard generated model files (for example, model.c or .cpp, model.h) or generate files that are independent of model code.
Organize generated code into sections (such as includes, typedefs, functions, and more). Your CFP template can emit code (for example, functions), directives (such as #define or #include statements), or comments into each section.
Generate custom file banners (comment sections) at the start and end of generated code files and custom function banners that precede functions in the generated code.
Generate code to call model functions, such as model_initialize, model_step, and so on.
Generate code to read and write model inputs and outputs.
Generate a main program module.
Obtain information about the model and the generated files from the model.
The custom file processing features are based on the following interrelated components:
Code generation template (CGT) files: a CGT file defines the top-level organization and formatting of generated code. See Code Generation Template (CGT) Files.
The code template API: a high-level Target Language Compiler (TLC) API that provides functions with which you can organize code into named sections and subsections of generated source and header files. The code template API also provides utilities that return information about generated files, generate standard model calls, and perform other functions. See Code Template API Summary.
Custom file processing (CFP) templates: a CFP template is a TLC file that manages the process of custom code generation. A CFP template assembles code to be generated into buffers. A CFP template also calls the code template API to emit the buffered code into specified sections of generated source and header files. A CFP template interacts with a CGT file, which defines the ordering of major sections of the generated code. See Use Custom File Processing (CFP) Templates.
To use CFP templates, you must understand TLC programming. See the Target Language Compiler document.
To use custom file processing features, create CGT files and CFP templates. These files are based on default templates provided by the code generation software. Once you have created your templates, you must integrate them into the code generation process.
Select and edit CGT files and CFP templates, and specify their use in the code generation process in the Code Generation > Templates pane of a model configuration set. The following figure shows all options configured for their defaults.
The options related to custom file processing are:
The Source file (.c) template field in the Code templates and Data templates sections. This field specifies the name of a CGT file to use when generating source (.c or .cpp) files. You must place this file on the MATLAB path.
The Header file (.h) template field in the Code templates and Data templates sections. This field specifies the name of a CGT file to use when generating header (.h) files. You must place this file on the MATLAB path.
By default, the template for both source and header files is matlabroot/toolbox/rtw/targets/ecoder/ert_code_template.cgt.
The File customization template edit field in the Custom templates section. This field specifies the name of a CFP template file to use when generating code files. You must place this file on the MATLAB path. The default CFP template is matlabroot/toolbox/rtw/targets/ecoder/example_file_process.tlc.
In each of these fields, click Browse to navigate to and select an existing CFP template or CGT file. Click Edit to open the specified file into the MATLAB editor where you can customize it.
CGT files have the following applications:
Generation of custom banners (comments sections) in code files. See Generate Custom File and Function Banners.
Advanced features, as described in Data, Function, and File Definition that use CGT files.
Generation of custom code using a CFP template requires a CGT file. To use CFP templates, you must understand the CGT file structure. In many cases, however, you can use the default CGT file without modifying it.
Default CGT file. The code generation software provides a default CGT file, matlabroot/toolbox/rtw/targets/ecoder/ert_code_template.cgt. Base your custom CGT files on the default file.
CGT File Structure. A CGT file consists of one required section and four optional sections:
Code Insertion Section.(Required) This section contains tokens that define an ordered partitioning of the generated code into a number of sections (such as Includes and Defines sections). Tokens have the form of:
%<SectionName>
For example,
%<Includes>
The code generation software defines a minimal set of required tokens. These tokens generate C or C++ source or header code. They are built-in tokens (see Built-In Tokens and Sections). You can also define custom tokens and custom sections.
Each token functions as a placeholder for a corresponding section of generated code. The ordering of the tokens defines the order in which the corresponding sections appear in the generated code. If you do not include a token, then the corresponding section is not generated. To generate code into a given section, explicitly call the code template API from a CFP template, as described in Use Custom File Processing (CFP) Templates.
The CGT tokens define the high-level organization of generated code. Using the code template API, you can partition each code section into named subsections, as described in Subsections.
In the code insertion section, you can also insert C or C++ comments between tokens. Such comments emit directly into the generated code.
File Banner Section.(Optional) This section contains comments and tokens you use in generating a custom file banner. See Generate Custom File and Function Banners.
Function Banner Section.(Optional) This section contains comments and tokens for use in generating a custom function banner. See???.
Shared Utility Function Banner Section.(Optional) This section contains comments and tokens for use in generating a custom shared utility function banner. See ???.
File Trailer Section.(Optional) This section contains comments for use in generating a custom trailer banner. See ???.
Built-In Tokens and Sections. The following code extract shows the required code insertion section of the default CGT file with the required built-in tokens.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Code insertion section (required) %% These are required tokens. You can insert comments and other tokens in %% between them, but do not change their order or remove them. %% %<Includes> %<Defines> %<Types> %<Enums> %<Definitions> %<Declarations> %<Functions>
Note the following requirements for customizing a CGT file:
Do not remove required built-in tokens.
Built-in tokens must appear in the order shown because each successive section has dependencies on previous sections.
Only one token per line.
Do not repeat tokens.
You can add custom tokens and comments to the code insertion section as long as you do not violate the previous requirements.
The following table summarizes the built-in tokens and corresponding section names, and describes the code sections.
Built-In CGT Tokens and Corresponding Code Sections
Token and Section Name | Description |
|---|---|
Includes | #include directives section |
Defines | #define directives section |
Types | typedef section. Typedefs can depend on any previously defined type |
Enums | Enumerated types section |
Definitions | Data definitions (for example, double x = 3.0;) |
Declarations | Data declarations (for example, extern double x;) |
Functions | C or C++ functions |
Subsections. You can define one or more named subsections for any section. Some of the built-in sections have predefined subsections summarized in ???.
Note Sections and subsections emit to the source or header file in the order listed in the CGT file. |
Using the custom section feature, you can define additional sections. See ???.
Subsections Defined for Built-In Sections
Section | Subsections | Subsection Description |
|---|---|---|
Includes | N/A |
|
Defines | N/A |
|
Types | IntrinsicTypes | Intrinsic typedef section. Intrinsic types depend only on intrinsic C or C++ types. |
Types | PrimitiveTypedefs | Primitive typedef section. Primitive typedefs depend only on intrinsic C or C++ types and on any typedefs previously defined in the IntrinsicTypes section. |
Types | UserTop | You can place any type of code in this section, including code that has dependencies on the previous sections. |
Types | Typedefs | typedef section. Typedefs can depend on any previously defined type |
Enums | N/A |
|
Definitions | N/A |
|
Declarations | N/A |
|
Functions |
| C or C++ functions |
Functions | CompilerErrors | #warning directives |
Functions | CompilerWarnings | #error directives |
Functions | Documentation | Documentation (comment) section |
Functions | UserBottom | You can place any code in this section. |
The files provided to support custom file processing are
matlabroot/rtw/c/tlc/mw/codetemplatelib.tlc: A TLC function library that implements the code template API. codetemplatelib.tlc also provides the comprehensive documentation of the API in the comments headers preceding each function.
matlabroot/toolbox/rtw/targets/ecoder/example_file_process.tlc: An example custom file processing (CFP) template, which you should use as the starting point for creating your own CFP templates. Guidelines and examples for creating a CFP template are provided in ???.
TLC files supporting generation of single-rate and multirate main program modules (see ???).
Once you have created a CFP template, you must integrate it into the code generation process, using the File customization template edit field (see ???).
A custom file processing (CFP) template imposes a simple structure on the code generation process. The template, a code generation template (CGT) file, partitions the code generated for each file into a number of sections. These sections are summarized in Built-In CGT Tokens and Corresponding Code Sections and Subsections Defined for Built-In Sections.
Code for each section is assembled in buffers and then emitted, in the order listed, to the file being generated.
To generate a file section, your CFP template must first assemble the code to be generated into a buffer. Then, to emit the section, your template calls the TLC function
LibSetSourceFileSection(fileH, section, tmpBuf)
where
fileH is a file reference to a file being generated.
section is the code section or subsection to which code is to be emitted. section must be one of the section or subsection names listed in Subsections Defined for Built-In Sections.
Determine the section argument as follows:
If Subsections Defined for Built-In Sections defines no subsections for a given section, use the section name as the section argument.
If Subsections Defined for Built-In Sections defines one or more subsections for a given section, you can use either the section name or a subsection name as the section argument.
If you have defined a custom token denoting a custom section, do not call LibSetSourceFileSection. Special API calls are provided for custom sections (see Generate a Custom Section).
tmpBuf is the buffer containing the code to be emitted.
There is no requirement to generate all of the available sections. Your template need only generate the sections you require in a particular file.
Note that no legality or syntax checking is performed on the custom code within each section.
The next section, Generate Source and Header Files with a Custom File Processing (CFP) Template, provides typical usage examples.
The files you generated in the previous procedures are organized according to the general code generation template. This template has the filename ert_code_template.cgt, and is specified by default in Code Generation > Templates pane of the Configuration Parameters dialog box.
The following fragment shows the rtwdemo_mpf.c file header that is generated using this default template:
/* * File: rtwdemo_mpf.c * * Code generated for Simulink model 'rtwdemo_mpf'. * * Model version : 1.88 * Simulink Coder version : 8.0 (R2011a) 26-Aug-2010 * TLC version : 7.6 (Sep 3 2010) * C/C++ source code generated on : Thu Sep 09 10:10:14 2010 * * Target selection: ert.tlc * Embedded hardware selection: Generic->32-bit Embedded Processor * Code generation objectives: Unspecified * Validation result: Not run */
You can change the organization of generated files using code templates and data templates. Code templates organize the files that contain functions, primarily. Data templates organize the files that contain identifiers. In this procedure, you organize the generated files, using the supplied MPF code and data templates:
In the Code templates section of the Templates pane, type code_c_template.cgt into the Source file (*.c) templates text box.
Type code_h_template.cgt into the Header file (*.h) templates text box.
In the Data templates section, type data_c_template.cgt into the Source file (*.c) templates text box.
Type data_h_template.cgt into the Header file (*.h) templates text box, and click Apply.
Click Generate code. Now the files are organized using the templates you specified. For example, the rtwdemo_mpf.c file header now is organized like this:
/** ******************************************************************************* ** FILE INFORMATION: ** Filename: rtwdemo_mpf.c ** File Creation Date: 09-Sep-2010 ** ** ABSTRACT: ** ** ** NOTES: ** ** ** MODEL INFORMATION: ** Model Name: rtwdemo_mpf ** Model Description: Data packaging examples ** Model Version: 1.89 ** Model Author: The MathWorks Inc. - Mon Mar 01 11:23:00 2004 ** ** MODIFICATION HISTORY: ** Model at Code Generation: ssulliva - Thu Sep 09 10:19:35 2010 ** ** Last Saved Modification: ssulliva - Thu Sep 09 10:19:13 2010 ** ** ******************************************************************************* **/
This section walks you through the process of generating a simple source (.c or .cpp) and header (.h) file using the example CFP template. Then, it examines the template and the code generated by the template.
The example CFP template, matlabroot/toolbox/rtw/targets/ecoder/example_file_process.tlc, demonstrates some of the capabilities of the code template API, including
Generation of simple source (.c or .cpp) and header (.h) files
Use of buffers to generate file sections for includes, functions, and so on
Generation of includes, defines, into the standard generated files (for example, model.h)
Generation of a main program module
Generate Code with a CFP Template. This section sets up a CFP template and configures a model to use the template in code generation. The template generates (in addition to the standard model files) a source file (timestwo.c or .cpp) and a header file (timestwo.h).
Follow the steps below to become acquainted with the use of CFP templates:
Copy the example CFP template, matlabroot/toolbox/rtw/targets/ecoder/example_file_process.tlc, to a folder outside of the MATLAB folder structure (that is, not under matlabroot). If the folder is not on the MATLAB path or the TLC path, then add it to the MATLAB path. It is good practice to locate the CFP template in the same folder as your system target file, which is on the TLC path.
Rename the copied example_file_process.tlc to test_example_file_process.tlc.
%% %assign ERTCustomFileTest = TLC_TRUE
It now reads:
%assign ERTCustomFileTest = TLC_TRUE
If ERTCustomFileTest is not assigned as shown, the CFP template is ignored in code generation.
Save your changes to the file. Keep test_example_file_process.tlc open, so you can refer to it later.
Open the rtwdemo_udt model.
Open the Simulink Model Explorer. Select the active configuration set of the model, and open the Code Generation pane of the active configuration set.
Specify File customization template as test_example_file_process.tlc. This is the file you previously edited and is now the specified CFP template for your model.
Select the Generate code only option.
Click Generate code. During code generation, notice the following message on the MATLAB command window:
Warning: Overriding example ert_main.c!
This message is displayed because test_example_file_process.tlc generates the main program module, overriding the default action of the ERT target. This is explained in greater detail below.
The rtwdemo_udt model is configured to generate an HTML code generation report. After code generation completes, view the report. Notice that the Generated Files list contains the files timestwo.c, timestwo.h, and ert_main.c. These files were generated by the CFP template. The next section examines the template to learn how this was done.
Keep the model, the code generation report, and the test_example_file_process.tlc file open so you can refer to them in the next section.
Analysis of the Example CFP Template and Generated Code. This section examines excerpts from test_example_file_process.tlc and some of the code it generates. Refer to the comments in matlabroot/rtw/c/tlc/mw/codetemplatelib.tlc while reading the following discussion.
Generating Code Files.Source (.c or .cpp) and header (.h) files are created by calling LibCreateSourceFile, as in the following excerpts:
%assign cFile = LibCreateSourceFile("Source", "Custom", "timestwo")
...
%assign hFile = LibCreateSourceFile("Header", "Custom", "timestwo")Subsequent code refers to the files by the file reference returned from LibCreateSourceFile.
File Sections and Buffers.The code template API lets you partition the code generated to each file into sections, tagged as Definitions, Includes, Functions, Banner, and so on. You can append code to each section as many times as required. This technique gives you a great deal of flexibility in the formatting of your custom code files.
Subsections Defined for Built-In Sections describes the available file sections and their order in the generated file.
For each section of a generated file, use %openfile and %closefile to store the text for that section in temporary buffers. Then, to write (append) the buffer contents to a file section, call LibSetSourceFileSection, passing in the desired section tag and file reference. For example, the following code uses two buffers (tmwtypesBuf and tmpBuf) to generate two sections (tagged "Includes" and "Functions") of the source file timestwo.c or .cpp (referenced as cFile):
%openfile tmwtypesBuf
#include "tmwtypes.h"
%closefile tmwtypesBuf
%<LibSetSourceFileSection(cFile,"Includes",tmwtypesBuf)>
%openfile tmpBuf
/* Times two function */
real_T timestwofcn(real_T input) {
return (input * 2.0);
}
%closefile tmpBuf
%<LibSetSourceFileSection(cFile,"Functions",tmpBuf)>These two sections generate the entire timestwo.c or .cpp file:
#include "tmwtypes.h"
/* Times two function */
FLOAT64 timestwofcn(FLOAT64 input)
{
return (input * 2.0);
}Adding Code to Standard Generated Files. The timestwo.c or .cpp file generated in the previous example was independent of the standard code files generated from a model (for example, model.c or .cpp, model.h, and so on). You can use similar techniques to generate custom code within the model files. The code template API includes functions to obtain the names of the standard models files and other model-related information. The following excerpt calls LibGetMdlPubHdrBaseName to obtain the name for the model.h file. It then obtains a file reference and generates a definition in the Defines section of model.h:
%% Add a #define to the model's public header file model.h
%assign pubName = LibGetMdlPubHdrBaseName()
%assign modelH = LibCreateSourceFile("Header", "Simulink", pubName)
%openfile tmpBuf
#define ACCELERATION 9.81
%closefile tmpBuf
%<LibSetSourceFileSection(modelH,"Defines",tmpBuf)>Examine the generated rtwdemo_udt.h file to see the generated #define directive.
Customizing Main Program Module Generation.Normally, the ERT target determines whether and how to generate an ert_main.c or .cpp module based on the settings of the Generate an example main program and Target operating system options on the Templates pane of the Configuration Parameters dialog box. You can use a CFP template to override the normal behavior and generate a main program module customized for your target environment.
To support generation of main program modules, two TLC files are provided:
bareboard_srmain.tlc: TLC code to generate an example single-rate main program module for a bareboard target environment. Code is generated by a single TLC function, FcnSingleTaskingMain.
bareboard_mrmain.tlc: TLC code to generate a multirate main program module for a bareboard target environment. Code is generated by a single TLC function, FcnMultiTaskingMain.
In the example CFP template file matlabroot/toolbox/rtw/targets/ecoder/example_file_process.tlc, the following code generates either a single- or multitasking ert_main.c or .cpp module. The logic depends on information obtained from the code template API calls LibIsSingleRateModel and LibIsSingleTasking:
%% Create a simple main. Files are located in MATLAB/rtw/c/tlc/mw. %if LibIsSingleRateModel() || LibIsSingleTasking() %include "bareboard_srmain.tlc" %<FcnSingleTaskingMain()> %else %include "bareboard_mrmain.tlc" %<FcnMultiTaskingMain()> %endif
Note that bareboard_srmain.tlc and bareboard_mrmain.tlc use the code template API to generate ert_main.c or .cpp.
When generating your own main program module, you disable the default generation of ert_main.c or .cpp. The TLC variable GenerateSampleERTMain controls generation of ert_main.c or .cpp. You can directly force this variable to TLC_FALSE. The examples bareboard_mrmain.tlc and bareboard_srmain.tlc use this technique, as shown in the following excerpt from bareboard_srmain.tlc.
%if GenerateSampleERTMain
%assign CompiledModel.GenerateSampleERTMain = TLC_FALSE
%warning Overriding example ert_main.c!
%endifAlternatively, you can implement a SelectCallback function for your target. A SelectCallback function is a MATLAB function that is triggered during model loading, and also when the user selects a target with the System Target File browser. Your SelectCallback function should deselect and disable the Generate an example main program option. This prevents the TLC variable GenerateSampleERTMain from being set to TLC_TRUE.
See the rtwgensettings Structure section for information on creating a SelectCallback function.
The following code illustrates how to deselect and disable the Generate an example main program option in the context of a SelectCallback function.
slConfigUISetVal(hDlg, hSrc, 'GenerateSampleERTMain', 'off'); slConfigUISetEnabled(hDlg, hSrc, 'GenerateSampleERTMain',0);
Note Creation of a main program for your target environment requires some customization; for example, in a bareboard environment you need to attach rt_OneStep to a timer interrupt. It is expected that you will customize either the generated code, the generating TLC code, or both. See Guidelines for Modifying the Main Program and Guidelines for Modifying rt_OneStep for further information. |
Generate a Custom Section. You can define custom tokens in a CGT file and direct generated code into an associated built-in section. This feature gives you additional control over the formatting of code within each built-in section. For example, you could add subsections to built-in sections that do not already define any subsections. All custom sections must be associated with one of the built-in sections: Includes, Defines, Types, Enums, Definitions, Declarations, or Functions. To create custom sections, you must
Add a custom token to the code insertion section of your CGT file.
In your CFP file:
Assemble code to be generated to the custom section into a buffer.
Declare an association between the custom section and a built-in section, with the code template API function LibAddSourceFileCustomSection.
Emit code to the custom section with the code template API function LibSetSourceFileCustomSection.
The following code examples illustrate the addition of a custom token, Myincludes, to a CGT file, and the subsequent association of the custom section Myincludes with the built-in section Includes in a CFP file.
Note If you have not already created custom CGT and CFP files for your model, copy the default template files matlabroot/toolbox/rtw/targets/ecoder/ert_code_template.cgt and matlabroot/toolbox/rtw/targets/ecoder/example_file_process.tlc to a work folder that is outside the MATLAB folder structure but on the MATLAB or TLC path, rename them (for example, add the prefix test_ to each file), and update the Templates pane of the Configuration Parameters dialog box to reference them. |
First, add the token Myincludes to the code insertion section of your CGT file. For example:
%<Includes> %<Myincludes> %<Defines> %<Types> %<Enums> %<Definitions> %<Declarations> %<Functions>
Next, in the CFP file, add code to generate include directives into a buffer. For example, in your copy of the example CFP file, you could insert the following section between the Includes section and the Create a simple main section:
%% Add a custom section to the model's C file model.c %openfile tmpBuf #include "moretables1.h" #include "moretables2.h" %closefile tmpBuf %<LibAddSourceFileCustomSection(modelC,"Includes","Myincludes")> %<LibSetSourceFileCustomSection(modelC,"Myincludes",tmpBuf)>
The LibAddSourceFileCustomSection function call declares an association between the built-in section Includes and the custom section Myincludes. Myincludes is a subsection of Includes. The LibSetSourceFileCustomSection function call directs the code in the tmpBuf buffer to the Myincludes section of the generated file. LibSetSourceFileCustomSection is syntactically identical to LibSetSourceFileSection.
In the generated code, the include directives generated to the custom section appear after other code directed to Includes.
#include "rtwdemo_udt.h" #include "rtwdemo_udt_private.h" /* #include "mytables.h" */ #include "moretables1.h" #include "moretables2.h"
Note The placement of the custom token in this example CGT file is arbitrary. By locating %<Myincludes> after %<Includes>, the CGT file specifies only that the Myincludes code appears after Includes code. |
Custom Tokens. Custom tokens are automatically translated to TLC syntax as a part of the build process. To escape a token, that is to prepare it for normal TLC expansion, use the '!' character. For example, the token %<!TokenName> is expanded to %<TokenName> by the template conversion program. Any valid TLC code can be specified, including TLC function calls: %<!MyTLCFcn()>.
The next figure shows part of a user-modified MPF template and the resulting generated code. This figure illustrates how you can use a template to
Define what code the code generation software should add to the generated file
Control the location of code in the file
Optionally insert comments in the generated file
Notice %<Includes>, for example, on the template. The term Includes is a symbol name. A percent sign and brackets (%< >) must enclose every symbol name. You can add the desired symbol name (within the %< > delimiter) at a particular location in the template. This is how you control where the code generator places an item in the generated file.

Mapping Template Specification to Code Generation
| This part of the template... | Generates in the file... | Explanation | ||
|---|---|---|---|---|
| Line | Description | |||
| (1) | /*#INCLUDES*/ %<Includes> | 26–28 | An /*#INCLUDES*/ comment, followed by #include statements | The code generator adds the C/C++ comment as a header, and then interprets the %<Includes> template symbol to list all the required #include statements in the file. This code is first in this section of the file because the template entries are first. |
| (2) | /*DEFINES*/ %<Defines> | 30 | A */DEFINES*/ comment, but no #define statements | Next, the code generator places the comment as a header for #define statements, but the file does not need #define. No code is added. |
| (3) | #pragma string1 | 31 | #pragma statements | While the code generator requires %<> delimiters for template symbols, it can also interpret C/C++ statements in the template without delimiters. In this case, the generator adds the specified statements to the code, following the order in which the statements appear in the template. |
| (5) | #pragma string2 | 42 | ||
| (4) | /#DEFINITIONS*/ %<Definitions> | 32–41 | /*#DEFINITIONS*/ comment, followed by definitions | The code generator places the comment and definitions in the file between the #pragma statements, according to the order in the template. It also inserts comments (lines 33 and 36) that are preset in the model's Configuration Parameters dialog box. |
| (6) | %<Declarations> | 43 | No declarations | The file needs no declarations, so the code generator does not generate any for this file. The template has no comment to provide a header. Line 43 is left blank. |
| (7) | %<Functions> | 44–74 | Functions | Finally, the code generator adds functions from the model, plus comments that are preset in the Configuration Parameters dialog box. But it adds no comments as a header for the functions, because the template does not have one. This code is last because the template entry is last. |
For a list of template symbols and the rules for using them, see Template Symbol Groups, Template Symbols, and Rules for Modifying or Creating a Template. To set comment options, from the Simulation menu, select Configuration Parameters. On the Configuration Parameters dialog box, select the Code Generation > Comments pane. For details, see Configuring a Model for Code Generation.
Code Template API Functions summarizes the code template API. See the source code in matlabroot/rtw/c/tlc/mw/codetemplatelib.tlc for detailed information on the arguments, return values, and operation of these calls.
Code Template API Functions
Function | Description |
|---|---|
LibGetNumSourceFiles | Returns the number of created source files (.c or .cpp and .h). |
LibGetSourceFileTag | Returns <filename>_h and <filename>_c for header and source files, respectively, where filename is the name of the model file. |
LibCreateSourceFile | Creates a new C or C++ file and returns its reference. If the file already exists, simply returns its reference. |
LibGetSourceFileFromIdx | Returns a model file reference based on its index. This is useful for a common operation on all files, such as to set the leading file banner of all files. |
LibSetSourceFileSection | Adds to the contents of a specified section within a specified file (see also Custom File Processing (CFP) Template Structure). |
LibIndentSourceFile | Indents a file with the c_indent utility (from within the TLC environment). |
LibCallModelInitialize | Returns code for calling the model's model_initialize function (valid for ERT only). |
LibCallModelStep | Returns code for calling the model's model_step function (valid for ERT only). |
LibCallModelTerminate | Returns code for calling the model's model_terminate function (valid for ERT only). |
LibCallSetEventForThisBaseStep | Returns code for calling the model's set events function (valid for ERT only). |
LibWriteModelData | Returns data for the model (valid for ERT only). |
LibSetRTModelErrorStatus | Returns the code to set the model error status. |
LibGetRTModelErrorStatus | Returns the code to get the model error status. |
LibIsSingleRateModel | Returns true if model is single rate and false otherwise. |
LibGetModelName | Returns name of the model (no extension). |
LibGetMdlSrcBaseName | Returns the name of model's main source file (for example, model.c or .cpp). |
LibGetMdlPubHdrBaseName | Returns the name of model's public header file (for example, model.h). |
LibGetMdlPrvHdrBaseName | Returns the name of the model's private header file (for example, model_private.h). |
LibIsSingleTasking | Returns true if the model is configured for single-tasking execution. |
LibWriteModelInput | Returns the code to write to a particular root input (that is, a model inport block). (valid for ERT only). |
LibWriteModelOutput | Returns the code to write to a particular root output (that is, a model outport block). (valid for ERT only). |
LibWriteModelInputs | Returns the code to write to root inputs (that is, all model inport blocks). (valid for ERT only) |
LibWriteModelOutputs | Returns the code to write to root outputs (that is, all model outport blocks). (valid for ERT only). |
LibNumDiscreteSampleTimes | Returns the number of discrete sample times in the model. |
LibSetSourceFileCodeTemplate | Set the code template to be used for generating a specified source file. |
LibSetSourceFileOutputDirectory | Set the folder into which a specified source file is to be generated. |
LibAddSourceFileCustomSection | Add a custom section to a source file. The custom section must be associated with one of the built-in (required) sections: Includes, Defines, Types, Enums, Definitions, Declarations, or Functions. |
LibSetSourceFileCustomSection | Adds to the contents of a specified custom section within a specified file. The custom section must have been previously created with LibAddSourceFileCustomSection. |
LibGetSourceFileCustomSection | Returns the contents of a specified custom section within a specified file. |
LibSetCodeTemplateComplianceLevel | This function must be called from your CFP template before any other code template API functions are called. Pass in 2 as the level argument. |
Using code generation template (CGT) files, you can specify custom file banners and function banners for the generated code files. File banners are comment sections in the header and trailer sections of a generated file. Function banners are comment sections for each function in the generated code. Use these banners to add a company copyright statement, specify a special version symbol for your configuration management system, remove time stamps, and for many other purposes. These banners can contain characters, which propagate to the generated code.
To specify banners, create a custom CGT file with customized banner sections. The build process creates an executable TLC file from the CGT file. The code generation process then invokes the TLC file.
You do not need to be familiar with TLC programming to generate custom banners. You can modify example files that are supplied with the ERT target.
Note Prior releases supported direct use of customized TLC files as banner templates. You specified these with the Source file (.c) banner template and Header file (.h) banner template options of the ERT target. You can still use a custom TLC file banner templates, however, you can now use CGT files instead. |
ERT template options on the Code Generation > Templates pane of a configuration set, in the Code templates section, support banner generation.
The options for function and file banner generation are:
Code templates: Source file (*.c) template: CGT file to use when generating source (.c or .cpp) files. Place this file on the MATLAB path.
Code templates: Header file (*.h) template: CGT file to use when generating header (.h) files. You must place this file on the MATLAB path. This file can be the same template specified in the Code templates: Source file (*.c) template field, in which case identical banners are generated in source and header files.
By default, the template for both source and header files is matlabroot/toolbox/rtw/targets/ecoder/ert_code_template.cgt.
In each of these fields, click Browse to navigate to and select an existing CGT file for use as a template. Click Edit to open the specified file into the MATLAB editor, where you can customize it.
Create a Custom File and Function Banner Template. To customize a CGT file for custom banner generation, make a local copy of the default code template and edit it, as follows:
Open the Code Generation pane of the active configuration set.
By default, the code template specified in the Code templates: Source file (*.c) template and Code templates: Header file (*.h) template fields is matlabroot/toolbox/rtw/targets/ecoder/ert_code_template.cgt.
If you want to use a different template as your starting point, click Browse to locate and select a CGT file.
Click Edit button to open the CGT file into the MATLAB editor.
Save a local copy of the CGT file. Store the copy in a folder that is outside of the MATLAB folder structure, but on the MATLAB path. If required, add the folder to the MATLAB path.
If you intend to use the CGT file with a custom target, locate the CGT file in a folder under your target root folder.
Rename your local copy of the CGT file. When you rename the CGT file, update the associated Code templates: Source file (*.c) template or Code templates: Header file (*.h) template field to match the new file name.
Edit and customize the local copy of the CGT file for banner generation, using the information provided in Customize a Code Generation Template (CGT) File for File and Function Banner Generation.
Save your changes to the CGT file.
Generate code. Examine the generated source and header files to confirm that they contain the banners specified by the template or templates.
Customize a Code Generation Template (CGT) File for File and Function Banner Generation. This section describes how to edit a CGT file for custom file and function banner generation. For a description of CGT files, see Code Generation Template (CGT) Files.
Components of the File and Function Banner Sections in the CGT file.In a CGT file, you can modify the following sections: file banner, function banner, shared utility function banner, and file trailer. Each section is defined by open and close tags. The tags specific to each section are shown in the following table.
| CGT File Section | Open Tag | Close Tag |
|---|---|---|
| File Banner | <FileBanner> | </FileBanner> |
| Function Banner | <FunctionBanner> | </FunctionBanner> |
| Shared-utility Banner | <SharedUtilityBanner> | </SharedUtilityBanner> |
| File Trailer | <FileTrailer> | </FileTrailer> |
You can customize your banners by including tokens and comments between the open and close tag for each section. Tokens are typically TLC variables, for example <ModelVersion>, which are replaced with values in the generated code.
Note Including C comment indicators, '/*' or a '*/', in the contents of your banner might introduce an error in the generated code. |
An open tag includes tag attributes. Enclose the value of the attribute in double quotes. The attributes available for an open tag are:
width: specifies the width of the file or function banner comments in the generated code. The default value is 80.
style: specifies the boundary for the file or function banner comments in the generated code. See for style options.
The open tag syntax is as follows:
<OpenTag style = "style_value" width = "num_width">
The built-in style options for the style attribute are:
classic
/* single line comments */ /* * multiple line comments * second line */
classic_cpp
// single line comments // // multiple line comments // second line //
box
/**********************************************************/ /* banner contents */ /**********************************************************/
box_cpp
//////////////////////////////////////////////////////////// // banner contents // ////////////////////////////////////////////////////////////
open_box
/********************************************************** * banner contents **********************************************************/
open_box_cpp
//////////////////////////////////////////////////////////// // banner contents ////////////////////////////////////////////////////////////
This section contains comments and tokens for use in generating a custom file banner. The file banner precedes any C or C++ code generated by the model. If you omit the file banner section from the CGT file, then no file banner emits to the generated code. The following section is the file banner section provided with the default CGT file, matlabroot/toolbox/rtw/targets/ecoder/ert_code_template.cgt.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Custom file banner section (optional) %% <FileBanner style="classic"> File: %<FileName> Code generated for Simulink model %<ModelName>. Model version : %<ModelVersion> Simulink Coder version : %<RTWFileVersion> TLC version : %<TLCVersion> C/C++ source code generated on : %<SourceGeneratedOn> %<CodeGenSettings> </FileBanner>
Summary of Tokens for File Banner Generation
FileName | Name of the generated file (for example, "rtwdemo_udt.c"). |
FileType | Either "source" or "header". Designates whether generated file is a .c or .cpp file or an .h file. |
FileTag | Given file names file.c or .cpp and file.h; the file tags are "file_c" and "file_h", respectively. |
ModelName | Name of generating model. |
ModelVersion | Version number of model. |
RTWFileVersion | Version number of model.rtw file. |
RTWFileGeneratedOn | Timestamp of model.rtw file. |
TLCVersion | Version of Target Language Compiler. |
SourceGeneratedOn | Timestamp of generated file. |
CodeGenSettings | Code generation settings for model: target language, target selection, embedded hardware selection, emulation hardware selection, code generation objectives (in priority order), and Code Generation Advisor validation result. |
This section contains comments and tokens for use in generating a custom function banner. The function banner precedes any C or C++ function generated during the build process. If you omit the function banner section from the CGT file, the default function banner emits to the generated code. The following section is the default function banner section provided with the default CGT file, matlabroot/toolbox/rtw/targets/ecoder/ert_code_template.cgt.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Custom function banner section (optional) %% Customize function banners by using the following predefined tokens: %% %<ModelName>, %<FunctionName>, %<FunctionDescription>, %<Arguments>, %% %<ReturnType>, %<GeneratedFor>, %<BlockDescription>. %% <FunctionBanner style="classic"> %<FunctionDescription> %<BlockDescription> </FunctionBanner>
Summary of Tokens for Function Banner Generation
FunctionName | Name of function |
Arguments | List of function arguments |
ReturnType | Return type of function |
ModelName | Name of generating model |
FunctionDescription | Short abstract about the function |
GeneratedFor | Full block path for the generated function |
BlockDescription | User input from the Block Description parameter of the block properties dialog box. BlockDescription contains an optional token attribute, style. The only valid value forstyle is content_only, which is case-sensitive and enclosed in double quotes. Use the content_only style when you want to include only the block description content that you entered in the block parameter dialog. The syntax for the token attribute style is: %<BlockDescription style = "content_only"> |
The shared utility function banner section contains comments and tokens for use in generating a custom shared utility function banner. The shared utility function banner precedes any C or C++ shared utility function generated during the build process. If you omit the shared utility function banner section from the CGT file, the default shared utility function banner emits to the generated code. The following section is the default shared utility function banner section provided with the default CGT file, matlabroot/toolbox/rtw/targets/ecoder/ert_code_template.cgt.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Custom shared utility function banner section (optional) %% Customize banners for functions generated in shared location by using the %% following predefined tokens: %<FunctionName>, %<FunctionDescription>, %% %<Arguments>, %<ReturnType>. %% <SharedUtilityBanner style="classic"> %<FunctionDescription> </SharedUtilityBanner>
Summary of Tokens for Shared Utility Function Banner Generation
FunctionName | Name of function |
Arguments | List of function arguments |
ReturnType | Return type of function |
FunctionDescription | Short abstract about function |
The file trailer section contains comments for generating a custom file trailer. The file trailer follows any C or C++ code generated from the model. If you omit the file trailer section from the CGT file, no file trailer emits to the generated code. The following section is the default file trailer provided in the default CGT file.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Custom file trailer section (optional) %% <FileTrailer style="classic"> File trailer for generated code. [EOF] </FileTrailer>
All of the tokens available for the file banner are available for the file trailer. See Summary of Tokens for File Banner Generation.
Introduction. Template Symbol Groups and Template Symbols describe MPF template symbols and rules for using them. The location of a symbol in one of the supplied template files (code_c_template.cgt, code_h_template.cgt, data_c_template.cgt, or data_h_template.cgt) determines where the items associated with that symbol are located in the corresponding generated file. Template Symbol Groups identifies the symbol groups, starting with the parent ("Base") group, followed by the children of each parent. Template Symbols lists the symbols alphabetically.
| Symbol Group | Symbol Names in This Group |
|---|---|
Base (Parents) | Declarations Defines Definitions Documentation Enums Functions Includes Types |
Declarations | ExternalCalibrationLookup1D ExternalCalibrationLookup2D ExternalCalibrationScalar ExternalVariableScalar |
Defines | LocalDefines LocalMacros |
Definitions | FilescopeCalibrationLookup1D FilescopeCalibrationLookup2D FilescopeCalibrationScalar FilescopeVariableScalar GlobalCalibrationLookup1D GlobalCalibrationLookup2D GlobalCalibrationScalar GlobalVariableScalar |
Documentation | Abstract Banner Created Creator Date Description FileName History LastModifiedDate LastModifiedBy ModelName ModelVersion ModifiedBy ModifiedComment ModifiedDate ModifiedHistory |
Notes ToolVersion | |
Functions | CFunctionCode |
Types | This parent has no children. |
| Symbol Name* | Symbol Group | Symbol Scope | Symbol Description (What the symbol puts in the generated file) |
|---|---|---|---|
Abstract | Documentation | N/A | User-supplied description of the model or file. Placed in the generated file based on the Stateflow note, Simulink annotation, or DocBlock on the model.** |
Banner | Documentation | N/A | Comments located near top of the file. Contains information that includes model and software versions, and date file was generated. |
CFunctionCode | Functions | File | All of the C/C++ functions. Must be at the bottom of the template. |
Created | Documentation | N/A | Date when model was created. From Created on field on Model Properties dialog box. |
Creator | Documentation | N/A | User who created model. From Created by field on Model Properties dialog box. |
Date | Documentation | N/A | Date file was generated. Taken from computer clock. |
Declarations | Base | Data declaration of any signal or parameter. For example, extern real_T globalvar;. | |
Defines | Base | File | Any required #defines of .h files. |
Definitions | Base | File | Data definition of any signal or parameter. |
Description | Documentation | N/A | Description of model. From Model description field on Model Properties dialog box.** |
Documentation | Base | N/A | Comments about how to interpret the generated files. |
Enums | Base | File | Enumerated data type definitions. |
ExternalCalibrationLookup1D | Declarations | External | *** |
ExternalCalibrationLookup2D | Declarations | External | *** |
ExternalCalibrationScalar | Declarations | External | *** |
ExternalVariableScalar | Declarations | External | *** |
FileName | Documentation | N/A | Name of the generated file. |
FilescopeCalibrationLookup1D | Definitions | File | *** |
FilescopeCalibrationLookup2D | Definitions | File | *** |
FilescopeCalibrationScalar | Definitions | File | *** |
FilescopeVariableScalar | Definitions | File | *** |
Functions | Base | File | Generated function code. |
GlobalCalibrationLookup1D | Definitions | Global | *** |
GlobalCalibrationLookup2D | Definitions | Global | *** |
GlobalCalibrationScalar | Definitions | Global | *** |
GlobalVariableScalar | Definitions | Global | *** |
History | Documentation | N/A | User-supplied revision history of the generated files. Placed in the generated file based on the Stateflow note, Simulink annotation, or DocBlock on the model.** |
Includes | Base | File | #include preprocessor directives. |
LastModifiedDate | Documentation | N/A | Date when model was last saved. From Last saved on field on Model Properties dialog box. |
LastModifiedBy | Documentation | N/A | User who last saved model. From Last saved by field on Model Properties dialog box. |
LocalDefines | Defines | File | #define preprocessor directives from code-generation data dictionary. |
LocalMacros | Defines | File | C/C++ macros local to the file. |
ModelName | Documentation | N/A | Name of the model. |
ModelVersion | Documentation | N/A | Version number of the Simulink model. |
ModifiedBy | Documentation | N/A | Name of user who last modified the model. From Model version field on Model Properties dialog box. |
ModifiedComment | Documentation | N/A | Comment user enters in the Modified Comment field on the Log Change dialog box. See Creating a Model Change History in the Simulink documentation. |
ModifiedDate | Documentation | N/A | Date model was last modified before code was generated. |
ModifiedHistory | Documentation | N/A | Text from Modified history field on Model Properties dialog box.** |
Notes | Documentation | N/A | User-supplied miscellaneous notes about the model or generated files. Placed in the generated file based on the Stateflow note, Simulink annotation, or DocBlock on the model.** |
ToolVersion | Documentation | N/A | A list of the versions of the toolboxes used in generating the code. |
Types | Base |
| Data types of generated code. |
* All symbol names must be enclosed between %< >. For example, %<Functions>.
** This symbol can be used to add a comment to the generated files. See Add Global Comments. The code generator places the comment in each generated file whose template has this symbol name. The code generator places the comment at the location that corresponds to where the symbol name is located in the template file.
*** The description can be deduced from the symbol name. For example, GlobalCalibrationScalar is a symbol that identifies a scalar. It contains data of global scope that you can calibrate .
Rules for Modifying or Creating a Template. The following are the rules for creating any MPF template. Comparison of a Template and Its Generated File illustrates several of these rules.
Place a symbol on a template within the %< > delimiter. For example, the symbol named Includes should look like this on a template: %<Includes>. Note that symbol names are case sensitive.
Place a symbol on a template where desired. Its location on the template determines where the item associated with this symbol is located in the generated file. If no item is associated with it, the symbol is ignored.
Place a C/C++ statement outside of the %< > delimiter, and on a different line than a %< > delimiter, for that statement to appear in the generated file. For example, #pragma message ("my text") in the template results in #pragma message ("my text") at the corresponding location in the generated file. Note that the statement must be compatible with your C/C++ compiler.
Use the .cgt extension for every template filename. ("cgt" stands for code generation template.)
Note that %% $Revision: 1.1.4.10.4.1 $ appears at the top of the MathWorks supplied templates. This is for internal MathWorks use only. It does not need to be placed on a user-defined template and does not show in a generated file.
Place a comment on the template between /* */ as in standard ANSI C[1] . This results in /*comment*/ on the generated file.
Each MPF template must have all of the Base group symbols, in predefined order. They are listed in Template Symbol Groups. Each symbol in the Base group is a parent. For example, Declarations is a parent symbol.
Each symbol in a non-Base group is a child. For example, LocalMacros is a child.
Except for Documentation children, all children must be placed after their parent, before the next parent, and before the Functions symbol.
Documentation children can be located before or after their parent in any order anywhere in the template.
If a non-Documentation child is missing from the template, the code generator places the information associated with this child at its parent location in the generated file.
If a Documentation child is missing from the template, the code generator omits the information associated with that child from the generated file.
This chapter focuses on module packaging features (MPF) settings that are interdependent. Their combined values, along with Simulink partitioning, determine the file placement of data definitions and declarations, or data placement. This includes
The number of files generated.
Whether or not the generated files contain definitions for a model's global identifiers. And, if a definition exists, the settings determine the files in which MPF places them.
Where MPF places global data declarations (extern).
The following six MPF settings are distributed among the main procedures and form an important interdependency:
The Data definition field on the Code Placement pane of the Configuration Parameters dialog box.
The Data declaration field on the Code Placement pane of the Configuration Parameters dialog box.
The Owner field of the data object in the Model Explorer and the checkbox for Use owner from data object for data definition placement on the Code Placement pane of the Configuration Parameters dialog box. The term "ownership settings" refers to these fields together.
The Definition file field of the data object on the Model Explorer.
The Header file field of the data object on the Model Explorer.
The Memory section field of the data object on the Model Explorer.
Overview. There is a priority order among interdependent MPF settings. From highest to lowest, the priorities are
Definition File priority
Header File priority
Ownership priority
Read-Write priority or Global priority
Priority order varies inversely with frequency of use, as illustrated below. For example, Definition File is highest priority but least used.
MPF Settings Priority and Usage

Unless they are overridden, the Read-Write and Global priorities place in the generated files all of the model's MPF-derived data objects that you selected using Data Object Wizard. (See Create Simulink Data Objects with Data Object Wizard for details.) Before generating the files, you can use the higher priority Definition file, Header file, and Ownership, as desired, to override Read-Write or Global priorities for single data objects. Most users will employ Read-Write or Global, without an override. A few users, however, will want to do an override for certain data objects. We expect that those users whose applications include multiple modules will want to use the Ownership priority.
The priorities are used only for those data objects that are derived from Simulink.Signal and Simulink.Parameter, and whose custom storage classes are specified using the Custom Storage Class Designer. (For details, see Design Custom Storage Classes and Memory Sections.) Otherwise, the build process determines the data placement.
Read-Write Priority. This is the lowest priority. Consider that a model consists of one or more Simulink blocks or Stateflow diagrams. There can be subsystems within these. For the purpose of illustration, think of a model with one top-level block called fuelsys. You double-clicked the block and now see three subsystems labeled subsys1, subsys2 and subsys3, as shown in the next figure. Signals a and b are outputs from the top-level block (fuelsys). Signal a is an input to subsys1 and b is input to subsys2. Signal c is an output from subsys1. Notice the other inputs and outputs (d and e). Signals a through e have corresponding data objects and are part of the code generation data dictionary.
As explained in Data Definition and Declaration Management, MPF provides you with the means of selecting a data object that you want defined as an identifier in the generated code. MPF also allows you to specify property values for each data object. For this illustration, we choose to include all of the data objects to be in the dictionary.

We generate code for this model. As shown in the figure below, this results in a .c source file corresponding to each of the subsystems. (In actual applications, there could be more than one .c source file for a subsystem. This is based on the file partitioning previously selected for the model. But for our illustration, we only need to show one for each subsystem.) Data objects a through e have corresponding identifiers in the generated files.
A .c source file has one or more functions in it, depending on the internal operations (functions) of its corresponding subsystem. An identifier in a generated .c file has local scope when it is used only in one function of that .c file. An identifier has file scope when more than one function in the same .c file uses it. An identifier has global scope when more than one of the generated files uses it.
A subsystem's source file always contains the definitions for all of that subsystem's data objects that have local scope or file scope. (These definitions are not shown in the figure.) But where are the definitions and declarations for data objects of global scope? These are shown in the next figure.

For the Read-Write priority, this source file contains the definitions for the subsystem's global data objects, if this is the file that first writes to the data object's address. Other files that read (use) that data object only include a reference to it. This is why this priority is called Read-Write. Since a read and a write of a file are analogous to input and output of a model's block, respectively, there is another way of saying this. The definitions of a block's global data objects are located in the corresponding generated file, if that data object is an output from that block. The declarations (extern) of a block's global data objects are located in the corresponding generated file, if that data object is an input to that block.
Settings for Read-Write Priority.The generated files and what they include, as just described, occur when the Read-Write priority is used. For this to be the case, the other priorities are turned off. That is,
The Data definition field on the Code Placement pane is set to Data defined in source file.
The Data declaration field on the Code Placement pane is set to Data declared in source file.
The Owner field on the Model Explorer is blank, and the checkbox for the Use owner from data object for data definition placement field on the Code Placement pane is not checked.
Definition file and Header file on the Model Explorer are blank.
Global Priority. This has the same priority as Read-Write (the lowest) priority. The settings for this are the same as for Read-Write Priority, except
The Data definition field on the Code Placement pane is set to Data defined in single separate source file.
The Data declaration field on the Code Placement pane is set to Data declared in single separate header file.
The generated files that result are shown in the next figure. A subsystem's data objects of local or file scope are defined in the .c source file where the subsystem's functions are located (not shown). The data objects of global scope are defined in another .c file (called global.c in the figure). The declarations for the subsystem's data objects of global scope are placed in a .h file (called global.h).
For example, all data objects of local and file scope for subsys1 are defined in subsys1.c. Signal c in the model is an output of subsys1 and an input to subsys2. So c is used by more than one subsystem and thus is a global data object. Because of the global priority, the definition for c (int c;) is in global.c. The declaration for c (extern int c;) is in global.h. Since subsys2 uses (reads) c, #include "global.h" is in subsys2.c.

Definition File, Header File, and Ownership Priorities. While the Read-Write and Global priorities operate on all MPF-derived data objects that you want defined in the generated code, the remaining priorities allow you to override the Read-Write or Global priorities for one or more particular data objects. There is a high-to-low priority among these remaining priorities — Definition File, Header File, and Ownership — for a particular data object, as shown in MPF Settings Priority and Usage
Ownership settings refers to the on or off setting specified using the Use owner from data object for data definition placement checkbox on the Code Placement pane of the Configuration Parameters dialog box, and the Owner field of a data object in the Model Explorer. These settings do not control what files are generated. These settings only specify definitions and extern statements. There are four possible configurations, as shown in Ownership Settings.
Memory sections allow you to specify storage directives for a data object. As shown in Parameter and Signal Property Values, the possible values for the Memory section property of a parameter or signal object are Default, MemConst, MemVolatile or MemConstVolatile.
If you specify a filename for Definition file, and select Default, MemConst, MemVolatile or MemConstVolatile for the Memory section property, the code generation software generates a .c file and an .h file. The .c file contains the definition for the data object with the pragma statement or qualifier associated with the Memory section selection. The .h file contains the declaration for the data object. The .h file can be included, using the preprocessor directive #include, in any file that needs to reference the data object.
You can add more memory sections. For more information, see Design Custom Storage Classes and Memory Sections and Memory Sections.
For a complete set of data placement rules in convenient tabular form, based on the priorities discussed in this chapter, see Data Placement Rules and Results.
Introduction. Example Settings and Resulting Generated Files provides example settings for one data object of a model. Eight examples are listed so that you can see the generated files that result from a wide variety of settings. Four examples from this table are discussed below in more detail. These discussions provide information for understanding settings you might choose. For illustration purposes, the four examples assume that we are dealing with an overall system that controls engine idle speed.
The next figure shows that the software component of this example system consists of two modules, IAC (Idle Air Control), and IO (Input-Output).

The code in the IO module controls the system's IO hardware. Code is generated only for the IAC module. (Some other means produced the code for the IO module, such as hand-coding.) So the code in IO is external to MPF, and can illustrate legacy code. To simplify matters, the IO code contains one source file, called IO.c, and one header file, called IO.h.
The IAC module consists of two Stateflow charts, spd_filt and iac_ctrl. The spd_filt chart has two signals (meas_spd) and filt_spd), and one parameter (a). The iac_ctrl chart also has two signals (filt_spd and iac_cmd) and a parameter (ref_spd). (The parameters are not visible in the top-level charts.) One file for each chart is generated. This example system allows us to illustrate referencing from file to file within the MPF module, and model to external module. It also illustrates the case where there is no such referencing.

Proceed to the discussion of the desired example settings:
Read-Write Example. These settings and the generated files that result are shown as Example Settings 1 in Example Settings and Resulting Generated Files. As you can see from the table, this example illustrates the case in which only one .c source file (for each chart) is generated.
So, for the IAC model, select the following settings. Accept the Data defined in source file in the Data definition field and the Data declared in source file in the Data declaration field on the Code Placement pane of the Configuration Parameters dialog box. Accept the default unchecked Use owner from data object for data definition placement field. Accept the default blank settings for the Owner, Definition file and Header file fields on the Model Explorer. For Memory section, accept Default. Now the Read-Write priority is active. Generate code. The next figure shows the results in terms of definition and declaration statements.

The code generator generated a spd_filt.c for the spd_filt chart and iac_ctrl.c for the iac_ctrl chart. As you can see, MPF placed all definitions of data objects for the spd_filt chart in spd_filt.c. It placed all definitions of data objects for the iac_ctrl chart in iac_ctrl.c.
However, notice real_T filt_spd. This data object is defined in spd_filt.c and declared in iac_ctrl.c. That is, since the Read-Write priority is active, filt_spd is defined in the file that first writes to its address. And, it is declared in the file that reads (uses) it. Further, real_T meas_spd is defined in both spd_filt.c and the external IO.c. And, real_T iac_cmd is defined in both iac_ctrl.c and IO.c.
Ownership Example. See tables Ownership Settings and Example Settings and Resulting Generated Files. In the Read-Write Example, there are several instances where the same data object is defined in more than one .c source file, and there is no declaration (extern) statement. This would result in compiler errors during link time. But in this example, we configure MPF Ownership rules so that linking can take place. Notice the Example Settings 2 row in Example Settings and Resulting Generated Files. Except for the ownership settings, assume these are the settings you made for the model in the IAC module. Since this example has no Definition file or Header file specified, now Ownership takes priority. (If you specified a Definition file or Header file, MPF ignores the ownership settings.)
On the Code Placement pane of the Configuration Parameters dialog box, check the box for the Use owner from data object for data definition placement field. Open the Model Explorer (by issuing the MATLAB command daexplr) and, for all data objects except meas_spd and iac_cmd, type IAC in the Owner field (case sensitive). Then, only for the meas_spd and iac_cmd data objects, type IO as their Owner (case sensitive). Generate code.
The results are shown in the next figure. Notice the extern real_T meas_spd statement in spd_filt.c, and extern real_T iac_cmd in iac_ctrl.c. MPF placed these declaration statements in the files where these data objects are used. This allows the generated source files (spd_filt.c and iac_ctrl.c) to be compiled and linked with IO.c.

Header File Example. These settings and the generated files that result are shown as Example Settings 3 in Example Settings and Resulting Generated Files. This example has no Definition file specified. If you specified a Definition file, MPF ignores the Header file setting. The focus of this example is to show how the Header file settings result in the linking of the two chart source files to the external IO files, shown in the next figure. (Also, ownership settings will be used to link the two chart files with each other.)
As you can see in the figure, the meas_spd and iac_cmd identifiers are defined in IO.c and declared in IO.h. Both of these identifiers are external to the generated .c files. You open the Model Explorer and select both the meas_spd and iac_cmd data objects. For each of these data objects, in the Header file field, specify IO.h, since this is where these two objects are declared. This setting allows the spd_filt.c source file to compile and link with the external IO.c file.
Now we configure the ownership settings. In the Model Explorer, select the filt_spd data object and set its Owner field to IAC. Then, on the Code Placement pane of the Configuration Parameters dialog box, check the box for the Use owner from data object for data definition placement field. Now the spd_filt source file links to the iac_ctrl source file. Generate code. See the figure below.

Since you specified the IO.h filename for the Header file field for the meas_spd and iac_ctrl objects, the code generator assumed that their declarations are in IO.h. So the code generator placed #include IO.h in each source file: spd_filt.c and iac_ctrl.c. So these two files will link with the external IO files. Also, due to the ownership settings that were specified, the code generator places the real_T filt_spd = 0.0; definition in spd_filt.c and declares the filt_spd identifier in iac_ctrl.c with extern real_T iac_cmd;. Consequently, the two source files will link together.
Definition File Example. These settings and the generated files that result are shown as Example Settings 4 in Example Settings and Resulting Generated Files. Notice that a definition filename is specified. The settings in the table only apply to the data object called a. You have decided that you do not want this object defined in spd_filt.c, the generated source file for the spd_filt chart. (There are many possible organizational reasons one might want an object declared in another file. It is not important for this example to specify the reason.)
For this example, assume the settings for all data objects are the same as those indicated in Header File Example, except for the data object a. The description below identifies only the differences that result from this.
Open the Model Explorer, and select data object a. In the Definition file field you specify any desired filename. Choose filter_constants.c. Generate code. The results are shown in the next figure.

The code generator generates the same files as in the Header File Example, and adds a new file, filter_constants.c. Data object a now is defined in filter_constants.c, rather than in the source file spd_filt.c, as it is in the example. This data object is declared with an extern statement in global.h
| Row Number | Enable Data Ownership Checkbox | Owner Setting | Result* |
|---|---|---|---|
1 | Off** | Blank** | Embedded Coder determines whether the current model defines data. |
2 | Off** | A name is specified. | Embedded Coder determines whether the current model defines data. |
3 | On | Blank** | Embedded Coder determines whether the current model defines data. |
4 | On | A name is specified. | The model specified in the Owner setting defines data. |
* See also Ownership Settings.
** Default.
Example Settings and Resulting Generated Files.
| Data Defined In... | Data Declared In... | Owner- ship* | Defined File** | Header File | Generated Files | |
|---|---|---|---|---|---|---|
Example Settings 1 | Source file | Source file | Blank | Blank | Blank | .c/.cpp source file |
Example Settings 2 (Owner- ship Example) | Source file | Source file | Name of module specified | Blank | Blank | .c/.cpp source file |
Example Settings 3 (Header File Example) | Source file | Source file | Blank | Blank | Desired include filename specified. | .c/.cpp source file |
Example Settings 4 (Def. File Example) | Source file | Source file | Blank | Desired definition filename specified. | Desired include filename specified. | .c/.cpp source file |
Example Settings 5 | Single separate source file | Source file | Blank | Blank | Blank | .c/.cpp source file |
Example Settings 6 | Single separate source file | Single separate header file | Blank | Blank | Blank | .c/.cpp source file |
Example Settings 7 | Single separate source file | Single separate header file | Name of module specified | Blank | Blank | .c/.cpp source file |
Example Settings 8 | Single separate source file | Single separate header file | Blank | Blank | Desired include filename specified. | .c/.cpp source file |
* "Blank" in ownership setting means that the check box for the Use owner from data object for data definition placement field on the Code Placement pane is Off and the Owner field on the Model Explorer is blank. "Name of module specified" can be a variety of ownership settings as defined in Ownership Settings.
** The code generator generates a definition .c/.cpp file for every data object for which you specified a definition filename (unless you selected #DEFINE for the Memory section field). For example, if you specify the same definition filename for all data objects, only one definition .c/.cpp file is generated. The code generator places declarations in model.h by default, unless you specify Data declared in single separate header file for the Data declaration option on the Code Generation > Code Placement pane of the Configuration Parameter dialog box. If you select that data placement option, the code generator places declarations in global.h. If you specify a definition filename for each data object, the code generator generates one definition .c/.cpp file for each data object and places declarations in model.h by default, unless you specify Data declared in single separate header file for Data declaration. If you select that data placement option, the code generator places declarations in global.h.
Note If you generate C++ rather than C code, the .c files listed in the following table will be .cpp files. |
| Global Settings: | Override Settings for Specific Data Object: | Results in Generated Files: | ||||||
|---|---|---|---|---|---|---|---|---|
Storage Class Setting | Data Def. | Data Dec. | Def. File | Owner | Header File | Where Data Def. Is | Where Data Dec. Is | Dec. Inclusion |
mpt or Simulink Noncustom Storage Classes: | ||||||||
auto | N/A | N/A | N/A | N/A | N/A | Note 12 | model.h | Note 1 |
Exported-Global | N/A | N/A | N/A | N/A | N/A | model.c | model.h | Note 1 |
Imported-Extern, Imported-Extern-Pointer | N/A | N/A | N/A | N/A | N/A | None. External | model_private.h | Note 2 |
Simulink-Global | N/A | N/A | N/A | N/A | N/A | Note 13 | model.h | Note 1 |
mpt or Simulink Custom Storage Class: Imported Data: | ||||||||
Imported-FromFile | D/C | D/C | D/C | N/A | null | None | model_private.h | Note 3 |
Imported-FromFile | D/C | D/C | D/C | N/A | hdr.h | None | model_private.h | Note 4 |
Simulink Custom Storage Class: #define Data: | ||||||||
Define | D/C | D/C | N/A | N/A | N/A | N/A | #define, model.h | Note 5 |
mpt Custom Storage Class: #define Data: | ||||||||
Define | D/C | D/C | N/A | N/A | null | N/A | #define, model.h | Note 5 |
Define | D/C | D/C | N/A | N/A | hdr.h | N/A | #define, model.h | Note 6 |
mpt or Simulink Custom Storage Class: GetSet: | ||||||||
GetSet | D/C | D/C | N/A | N/A | hdr.h | N/A | External hdr.h | Note 4 |
mpt or Simulink Custom Storage Class: Bitfield, Struct: | ||||||||
Bitfield, Struct | D/C | D/C | N/A | N/A | N/A | model.c | model.h | Note 7 |
mpt Custom Storage Class: Global, Const, ConstVolatile, Volatile: | ||||||||
Global, Const, Const-Volatile, Volatile | auto | auto | null | null or locally owned | null | model.c | model.h | Note 1 |
Global, Const, Const-Volatile, Volatile | src | auto | null | null or locally owned | null | src.c | model.h | Note 1 |
Global, Const, Const-Volatile, Volatile | sep | auto | null | null or locally owned | null | gbl.c | model.h | Note 1 |
Global, Const, Const-Volatile, Volatile | auto | src | null | null or locally owned | null | model.c | src.c | Note 8 |
Global, Const, Const-Volatile, Volatile | src | src | null | null or locally owned | null | src.c | src.c | Note 8 |
Global, Const, Const-Volatile, Volatile | sep | src | null | null or locally owned | null | gbl.c | src.c | Note 8 |
Global, Const, Const-Volatile, Volatile | auto | sep | null | null or locally owned | null | model.c | gbl.h | Note 9 |
Global, Const, Const-Volatile, Volatile | src | sep | null | null or locally owned | null | src.c | gbl.h | Note 9 |
Global, Const, Const-Volatile, Volatile | sep | sep | null | null or locally owned | null | gbl.c | gbl.h | Note 9 |
Global, Const, Const-Volatile, Volatile | D/C | D/C | data.c | D/C | null | data.c | See Note 10. | Note 10 |
Global, Const, Const-Volatile, Volatile | D/C | D/C | data.c | D/C | hdr.h | data.c | hdr.h | Note 11 |
Global, Const, Const-Volatile, Volatile | auto | D/C | null | null | hdr.h | model.c | hdr.h | Note 11 |
Global, Const, Const-Volatile, Volatile | src | D/C | null | null | hdr.h | src.c | hdr.h | Note 11 |
Global, Const, Const-Volatile, Volatile | sep | D/C | null | null | hdr.h | gbl.c | hdr.h | Note 11 |
Global, Const, Const-Volatile, Volatile | D/C | auto | null | External owner | null | External user-supplied file | model.h | Note 1 |
Global, Const, Const-Volatile, Volatile | D/C | src | null | External owner | null | External user-supplied file | src.c | Note 8 |
Global, Const, Const-Volatile, Volatile | D/C | sep | null | External owner | null | External user-supplied file | gbl.h | Note 9 |
Global, Const, Const-Volatile, Volatile | D/C | D/C | null | External owner | header.h | External user-supplied file | hdr.h | Note 11 |
| Global, Const, Const-Volatile, Volatile | D/C | D/C | null | External owner | header.h | External user-supplied file | hdr.h | Note 11 |
mpt Custom Storage Class: Exported Data: | ||||||||
ExportTo-File | auto | auto | null | null | null | model.c | model.h | Note 1 |
ExportTo-File | src | auto | null | null | null | src.c | model.h | Note 1 |
ExportTo-File | sep | auto | null | null | null | gbl.c | model.h | Note 1 |
ExportTo-File | auto | src | null | null | null | model.c | src.c | Note 8 |
ExportTo-File | src | src | null | null | null | src.c | src.c | Note 8 |
ExportTo-File | sep | src | null | null | null | gbl.c | src.c | Note 8 |
ExportTo-File | auto | sep | null | null | null | model.c | gbl.h | Note 9 |
ExportTo-File | src | sep | null | null | null | src.c | gbl.h | Note 9 |
ExportTo-File | sep | sep | null | null | null | gbl.c | gbl.h | Note 9 |
ExportTo-File | D/C | D/C | data.c | null | null | data.c | See Note 10. | Note 10 |
ExportTo-File | D/C | D/C | data.c | null | hdr.h | model.c | hdr.h | Note 11 |
ExportTo-File | auto | D/C | null | null | hdr.h | src.c | hdr.h | Note 11 |
ExportTo-File | sep | D/C | null | null | hdr.h | gbl.c | hdr.h | Note 11 |
Simulink Custom Storage Class: Default, Const, ConstVolatile, Volatile: | ||||||||
Default, Const, Const-Volatile, Volatile | auto | auto | N/A | N/A | N/A | model.c | model.h | Note 1 |
Default, Const, Const-Volatile, Volatile | src | auto | N/A | N/A | N/A | src.c | model.h | Note 1 |
Default, Const, Const-Volatile, Volatile | sep | auto | N/A | N/A | N/A | gbl.c | model.h | Note 1 |
Default, Const, Const-Volatile, Volatile | auto | src | N/A | N/A | N/A | model.c | src.c | Note 8 |
Default, Const, Const-Volatile, Volatile | src | src | N/A | N/A | N/A | src.c | src.c | Note 8 |
Default, Const, Const-Volatile, Volatile | sep | src | N/A | N/A | N/A | gbl.c | src.c | Note 8 |
Default, Const, Const-Volatile, Volatile | auto | sep | N/A | N/A | N/A | model.c | gbl.h | Note 9 |
Default, Const, Const-Volatile, Volatile | src | sep | N/A | N/A | N/A | src.c | gbl.h | Note 9 |
Default, Const, Const-Volatile, Volatile | sep | sep | N/A | N/A | N/A | gbl.c | gbl.h | Note 9 |
Simulink Custom Storage Class: Exported Data: | ||||||||
ExportTo-File | auto | auto | N/A | N/A | null | model.c | model.h | Note 1 |
ExportTo-File | src | auto | N/A | N/A | null | src.c | model.h | Note 1 |
ExportTo-File | sep | auto | N/A | N/A | null | gbl.c | model.h | Note 1 |
ExportTo-File | auto | src | N/A | N/A | null | model.c | src.c | Note 8 |
ExportTo-File | src | src | N/A | N/A | null | src.c | src.c | Note 8 |
ExportTo-File | sep | src | N/A | N/A | null | gbl.c | src.c | Note 8 |
ExportTo-File | auto | sep | N/A | N/A | null | model.c | gbl.h | Note 9 |
ExportTo-File | src | sep | N/A | N/A | null | src.c | gbl.h | Note 9 |
ExportTo-File | sep | sep | N/A | N/A | null | gbl.c | gbl.h | Note 9 |
ExportTo-File | auto | D/C | N/A | N/A | hdr.h | model.c | hdr.h | Note 11 |
ExportTo-File | src | D/C | N/A | N/A | hdr.h | src.c | hdr.h | Note 11 |
ExportTo-File | sep | D/C | N/A | N/A | hdr.h | gbl.c | hdr.h | Note 11 |
In the previous table:
A Declaration Inclusion Approach is a file in which the header file that contains the data declarations is included.
D/C stands for don't care.
Dec stands for declaration.
Def stands for definition.
gbl stands for global.
hdr stands for header.
N/A stands for not applicable.
null stands for field is blank.
sep stands for separate.
Note 1: model.h is included directly in all source files.
Note 2: model_private.h is included directly in all source files.
Note 3: extern is included in model_private.h, which is in source.c.
Note 4: header.h is included in model_private.h, which is in source.c.
Note 5: model.h is included directly in all source files that use #define.
Note 6: header.h is included in model.h, which is in source files that use #define.
Note 7: model.h is included in all source.c files.
Note 8: extern is inlined in source files where data is used.
Note 9: global.h is included in model.h, which is in all source files.
Note 10: When you specify a definition filename for a data object, no header file is generated for that data object. The code generator declares the data object according to the data placement priorities.
Note 11: header.h is included in model.h, which is in all source files.
Note 12: Signal: Either not defined because it is expression folded, or local data, or defined in a structure in model.c, all depending on model's code generation settings. Parameter: Either inlined in the code, or defined in model_data.c.
Note 13: Signal: In a structure that is defined in model.c. Parameter: In a structure that is defined in model_data.c.
Understanding the purpose of this procedure requires understanding the Header file property of a data object, described in Parameter and Signal Property Values, and applied in Create mpt Data Objects with Data Object Wizard. For a particular data object, you can specify as the Header file property value a .h filename where that data object will be declared. Then, in the IncludeFile section of the generated file, this .h file is indicated in a #include preprocessor directive.
Further, when specifying the filename as the Header file property value, you may or may not place it within the double-quote or angle-bracket delimiter. That is, you can specify it as filename.h, "filename.h", or <filename.h>. The code generator finds every data object for which you specified a filename as its Header file property value without a delimiter. By default, it assigns to each of these the double-quote delimiter.
This procedure allows you to specify the angle-bracket delimiter for these instead of the default double-quote delimiter. See the figure below.
In the #include file delimiter field on the Code Placement pane of the Configuration Parameters dialog box, select #include <header.h> instead of the default #include "header.h".
[1] ANSI is a registered trademark of the American National Standards Institute, Inc.
![]() | Target | Configuration Variations | ![]() |

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 |