Creating and linking variables
Once you have created a Retain Handler in TwinCAT, you can declare variables in the PLC and link them to the Retain Handler. The variables have to be identified in the PLC with the keyword VAR_RETAIN
.
If self-defined data types (DUTs) are used as retain data, the data types must be available in the TwinCAT type system. To do this, the structures must be created directly as STRUCT RETAIN
, with all occurrences of the structure then handled by the Retain Handler.

Retain data cannot be used for POUs (function blocks) as a whole. However, individual elements of a POU can be used.
Prerequisite for this step:
- A PLC project created in TwinCAT.
Create variables as follows:
- 1. Create the variables in your PLC project in a VAR RETAIN area.
- 2. For self-defined Data Unit Types (DUTs), use the keyword
STRUCT RETAIN
. - 3. Click on Build in the toolbar at the top, then on Build Solution
. - 4. Click on your PLC Instance in the tree view on the left and then on the tab Data Area.
- 5. Under Retain Hdl, select the Retain Handler that you have created.
- After selecting a Retain Handler as the target, the symbols are linked in the tree view and a mapping is created.
In the tree view, the PLC variables are created under the Retain Handler and linked to the PLC instance variables.
An existing link is indicated by an arrow icon.