Products & Services Solutions Academia Support User Community Company

Learn more about Real-Time Workshop Embedded Coder   

Configuring Templates for Customizing Code Organization and Format

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 moduleSelect Generate an example main program. For more information, see Generating a Standalone Program.

Overview

This section describes Real-Time Workshop Embedded Coder custom file processing (CFP) features. Custom file processing simplifies generation of custom source code. You can:

Custom File Processing Components

The custom file processing features are based on the following interrelated components:

To use CFP templates, you must understand TLC programming. See the Target Language Compiler document.

Custom File Processing User Interface Options

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:

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

Code Generation Template (CGT) Files

CGT files have the following applications:

Default CGT file

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.

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 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.

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:

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 Subsections Defined for Built-In Sections.

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.

Using Custom File Processing (CFP) Templates

The files provided to support custom file processing are

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).

Custom File Processing (CFP) Template Structure

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

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.

Changing the Organization of a Generated File

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:

  1. Display the active Real-Time Workshop Templates configuration parameters.

  2. In the Code templates section of the Templates pane, type code_c_template.cgt into the Source file (*.c) templates text box.

  3. Type code_h_template.cgt into the Header file (*.h) templates text box.

  4. In the Data templates section, type data_c_template.cgt into the Source file (*.c) templates text box.

  5. Type data_h_template.cgt into the Header file (*.h) templates text box, and click Apply.

  6. 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
     **
     **
     ************************************************************************
     **/

Generating Source and Header Files with a Custom File Processing (CFP) Template

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

Generating 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:

  1. 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.

  2. Rename the copied example_file_process.tlc to test_example_file_process.tlc.

  3. Open test_example_file_process.tlc into the MATLAB editor.

  4. Uncomment the following line:

    %%  %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.

  5. Save your changes to the file. Keep test_example_file_process.tlc open, so you can refer to it later.

  6. Open the rtwdemo_udt model.

  7. 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.

  8. Click the Templates tab.

  9. 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.

  10. Select the Generate code only option.

  11. Click Apply.

  12. 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.

  13. 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.

  14. 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 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:

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!
%endif

Alternatively, 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);

Generating 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

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.

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"

Comparison of a Template and Its Generated File

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

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.

Template and Generated File

How the Template Affects Code Generation

This part of the template...Generates in the file...Explanation
LineDescription
(1)/*#INCLUDES*/ %<Includes>26–28An /*#INCLUDES*/ comment, followed by #include statementsThe 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>30A */DEFINES*/ comment, but no #define statementsNext, 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 string131#pragma statementsWhile 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 string242
(4)/#DEFINITIONS*/ %<Definitions>32–41/*#DEFINITIONS*/ comment, followed by definitionsThe 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>43No declarationsThe 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–74FunctionsFinally, 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 Summary

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.

Generating Custom File and Function Banners

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.

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:

Creating 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:

  1. Activate the configuration set you that want to work with.

  2. Open the Real-Time Workshop pane of the active configuration set.

  3. Click the Templates tab.

  4. 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.

  5. If you want to use a different template as your starting point, click Browse to locate and select a CGT file.

  6. Click Edit button to open the CGT file into the MATLAB editor.

  7. 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.

  8. If you intend to use the CGT file with a custom target, locate the CGT file in a folder under your target root directory.

  9. 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.

  10. 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.

  11. Save your changes to the CGT file.

  12. Click Apply to update the configuration set.

  13. Save your model.

  14. Generate code. Examine the generated source and header files to confirm that they contain the banners specified by the template or templates.

Customizing 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 SectionOpen TagClose 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.

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 valueExample

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 Symbols and Rules

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.

Template Symbol Groups

Symbol GroupSymbol 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.

Template Symbols

Symbol Name*Symbol GroupSymbol ScopeSymbol 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 .

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.

  1. 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.

  2. 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.

  3. 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.

  4. Use the .cgt extension for every template filename. ("cgt" stands for code generation template.)

  5. 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.

  6. Place a comment on the template between /* */ as in standard ANSI C[1] . This results in /*comment*/ on the generated file.

  7. 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.

  8. Each symbol in a non-Base group is a child. For example, LocalMacros is a child.

  9. Except for Documentation children, all children must be placed after their parent, before the next parent, and before the Functions symbol.

  10. Documentation children can be located before or after their parent in any order anywhere in the template.

  11. 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.

  12. 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.

  


Related Products & Applications

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