| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → Real-Time Workshop Embedded Coder |
| Contents | Index |
| Learn more about Real-Time Workshop Embedded Coder |
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 Using Custom File Processing (CFP) Templates. |
| Generate a model-specific example main program module | Select Generate an example main program. For more information, see Generating a Standalone Program. |
This section describes Real-Time Workshop 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 Using 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 Real-Time Workshop Embedded Coder 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 Real-Time Workshop > Templates pane of a model configuration set. The following figure shows all options configured for their defaults.
Real-Time Workshop: Templates Pane

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. You must place this file on the
CGT files have the following applications:
Generation of custom banners (comments sections) in code files. See Generating Custom File and Function Banners.
Advanced features, as described in Defining Data Representation and Storage for Code Generation that use CGT files.
Generation of custom code using a CFP template requires a CGT file. To correctly use CFP templates, you must understand the CGT file structure. In many cases, however, you can use the default CGT file without modifying it.
The Real-Time Workshop Embedded Coder software provides a default CGT file, matlabroot/toolbox/rtw/targets/ecoder/ert_code_template.cgt. Base your custom CGT files on the default file.
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 Real-Time Workshop Embedded Coder 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 add them to the code insertion section (see Generating a Custom Section).
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. A token in the CGT file does not guarantee that the corresponding section is generated. To generate code into a given section, explicitly call the code template API from a CFP template, as described in Using 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 Generating Custom File and Function Banners.
Function Banner Section. (Optional) This section contains comments and tokens for use in generating a custom function banner. SeeGenerating Custom File and Function Banners.
Shared Utility Function Banner Section. (Optional) This section contains comments and tokens for use in generating a custom shared utility function banner. See Generating Custom File and Function Banners.
File Trailer Section. (Optional) This section contains comments for use in generating a custom trailer banner. See Generating Custom File and Function Banners.
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 |
You can define one or more named subsections for any section. Some of the built-in sections have predefined subsections summarized in Subsections Defined for Built-In Sections.
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 Generating a Custom Section.
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 Generating Source and Header Files with a Custom File Processing (CFP) Template.
TLC files supporting generation of single-rate and multirate main program modules (see Customizing Main Program Module Generation).
Once you have created a CFP template, you must integrate it into the code generation process, using the File customization template edit field (see Custom File Processing User Interface Options).
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 Generating 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, Generating 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 Real-Time Workshop Embedded Coder template. This template has the filename ert_code_template.cgt, and is specified by default in 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 * * Real-Time Workshop code generated for Simulink model rtwdemo_mpf. * * Model version : 1.87 * Real-Time Workshop file version : 7.3 (R2009a) 20-Nov-2008 * Real-Time Workshop file generated on : Wed Dec 17 16:27:14 2008 * TLC version : 7.3 (Nov 26 2008) * C/C++ source code generated on : Wed Dec 17 16:27:14 2008 */
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:
Display the active Real-Time Workshop Templates configuration parameters.
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: 17-Dec-2008 ** ** ABSTRACT: ** ** ** NOTES: ** ** ** MODEL INFORMATION: ** Model Name: rtwdemo_mpf ** Model Description: Data packaging examples ** Model Version: 1.87 ** Model Author: The MathWorks Inc. - Mon Mar 01 11:23:00 2004 ** ** MODIFICATION HISTORY: ** Model at Code Generation: username - Wed Dec 17 16:47:16 2008 ** ** Last Saved Modification: username - Wed Dec 17 15:23:20 2008 ** ** ************************************************************************ **/
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
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 directory outside the MATLAB directory structure (that is, not under matlabroot). If the directory 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 directory as your system target file, which is guaranteed to be 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 Real-Time Workshop pane of the active configuration set.
Configure the File customization template field as shown below. The test_example_file_process.tlc file, which you previously edited, 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 Source 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.
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 correct 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 an M-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 of the Developing Embedded Targets document 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. |
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 directory that is outside the MATLAB directory 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 correctly 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. In effect, 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 ensures only that the Myincludes code appears after Includes code. |
The next figure shows part of a user-modified MPF template and the resulting Real-Time Workshop Embedded Coder generated code. This figure illustrates how you can use a template to
Define what code the Real-Time Workshop Embedded Coder 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.

How the Template Affects 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 necessary #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 needed 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 Real-Time Workshop > Comments pane. For details, see Configuring a Model for Code Generation in the Real-Time Workshop documentation.
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 Real-Time Workshop 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 directory 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 Real-Time Workshop > Templates pane of a configuration set, in the Code templates section, support banner generation.
Real-Time Workshop: Templates Pane

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.
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 Real-Time Workshop 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 directory that is outside of the MATLAB directory structure, but on the MATLAB path. If necessary, add the directory 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 directory.
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 Customizing 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.
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 Function 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. |
The open tag can include a tag attribute called style, which specifies the boundary for the file or function banner comments in the generated code. Enclose the value of the style attribute in single or double quotes. The open tag syntax is:
<OpenTag style = "StyleValue">
You can choose from several built-in styles.
| Style value | Example |
|---|---|
classic style | /* single line comments */ /* * Multi-line comments * Second line */ |
classic_cpp | // single line comments // // multiple line contents // second line // |
box | /**********************************************************/ /* banner contents */ /**********************************************************/ |
box_cpp | //////////////////////////////////////////////////////////// // banner contents // //////////////////////////////////////////////////////////// |
open_box | /********************************************************** * banner contents **********************************************************/ |
open_box_cpp | //////////////////////////////////////////////////////////// // banner contents //////////////////////////////////////////////////////////// |
File Banner. 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> Real-Time Workshop code generated for Simulink model %<ModelName>. Model version : %<ModelVersion> Real-Time Workshop file version : %<RTWFileVersion> Real-Time Workshop file generated on : %<RTWFileGeneratedOn> 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. |
Function Banner. 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 |
Generated For | Full block path for the generated function |
BlockDescription | User input block description |
Shared Utility Function Banner. 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 |
File Trailer. 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 Real-Time Workshop 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.
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 Real-Time Workshop 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 necessary #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 Real-Time Workshop 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 Adding 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 .
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.
[1] ANSI is a registered trademark of the American National Standards Institute, Inc.
![]() | Controlling Code Style | Configuring the Placement of Data in Generated Code | ![]() |

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