Main Content

Resolve Error: Code Generator Failed to Produce C++ Destructor for MATLAB Class

Issue

Generating reentrant code with C++ classes from MATLAB® code increases the chances of stack overflow during code execution. Code generation might stop and produce this message:

Code generator failed to produce C++ destructor for MATLAB class 'y'. Generated code is not exception-safe. To enable generation of C++ destructor, disable 'Generate Re-entrant code (MultiInstanceCode)' configuration parameter.

This message might appear if both these conditions are true:

  • You choose to generate C++ code with classes from MATLAB code by setting TargetLang to 'C++' and CppPreserveClasses to true in the configuration object (coder.CodeConfig or coder.EmbeddedCodeConfig), or in the project build settings, by setting Language to C++and checking the Generate C++ classes from MATLAB classes check box.

  • You choose to generate reentrant code by enabling the MultiInstanceCode parameter in a code configuration object, or by enabling the Generate re-entrant code parameter in the Memory tab of the MATLAB Coder™ app.

  • The destructor of a class in your MATLAB code has a persistent variable or calls another function that declares and uses a persistent variable.

Possible Solutions

Depending on whether the type of code you want to generate, try one of these solutions.

Raise the Stack Limit

You can raise the stack limit to generate reentrant code that has C++ classes for MATLAB classes. Do one of the following:

  • In the project settings dialog box under the Memory tab, set the Stack usage max parameter.

  • In the configuration object for standalone code generation (coder.CodeConfig or coder.EmbeddedCodeConfig), set the StackUsageMax parameter.

Raise the stack limit by doubling the stack value until code generation succeeds, indicating that the code generator generated C++ classes in the reentrant code.

Note

The maximum configurable stack limit depends on the linker in your system. The default stack size varies based on your operating system and system configuration.

The destructor of a class in your MATLAB code must not have a persistent variable or call another function that declares a persistent variable.

Disable Reentrant Code

To generate code that contains C++ classes for MATLAB classes, you can disable generation of reentrant code. Do one of the following:

  • In the code configuration object, disable the MultiInstanceCode parameter.

  • In the MATLAB Coder app, disable the Generate re-entrant code parameter.

Generate Structures Instead of Classes

You can change the default behavior of the code generator to produce structures for MATLAB classes. Do one of the following:

  • In the MATLAB Coder app, set Language to C++. In the project build settings, clear the Generate C++ classes from MATLAB classes check box.

Related Topics