A Non-Obvious Pitfall with Resource Cleanup in TwinCAT Programs
Why FB_init and FB_exit inside TwinCAT programs (static classes) are not called automatically, and how to bypass this limitation.
By resource cleanup, I mean things like freeing dynamically allocated memory, closing a file handler, closing a connection, and similar operations.
This issue primarily affects TwinCAT versions 3.1.4024 and earlier, because these versions allowed developers to create FB_init and FB_exit methods directly inside programs. The trap is that these methods are not called automatically.
If you need to release resources when a program is deleted, here is an approach I can propose:
- Create an internal method inside the program dedicated to resource cleanup, for example
ReleaseResources(). - Create a dedicated class responsible solely for resource cleanup, for example
MainProgramResourceManager. - Implement
FB_exitinside this class, and call the program’s cleanup method from it, for exampleMAIN.ReleaseResources(). - Instantiate this class inside the program, for example:
_resourcemanager : MainProgramResourceManager;
That’s it. When the program is deleted, all its internal variables—including the resource manager—are deleted automatically. And since the resource manager is an object, its FB_exit method will be called automatically as well. This allows you to bypass this compiler limitation.
The same principle can be applied to initialization logic too.

#TwinCAT #CoDeSys #OOP #StructuredText #IndustrialAutomation