Customize Enumerated Types in Generated Code - MATLAB & Simulink (original) (raw)
To customize an enumeration in the generated code, in the static methods section of the MATLAB® enumeration class definition, provide customized versions of the methods listed in this table. The table also lists:
- The default value returned by a method, if you do not explicitly implement the method in your MATLAB enumeration class definition. If you do not provide an implementation, the code generator assumes that the method returns this default value.
- All possible values a method can return and their effects on the generated code.
Method | Description | Return values |
---|---|---|
generateEnumClass | Specifies whether to generate enumeration classes. See Generate C++ Code That Contains Ordinary C Enumeration. | true (default) — The generated C++ code contains enumeration classes.false — The generated C++ code contains ordinary C style enumerations. |
addClassNameToEnumNames | Specifies whether the class name becomes a prefix in the generated code. See Include Class Name Prefix in Generated Enumeration Value Names. | false (default) — Prefix is not used.true — Prefix is used. |
generatedCodeIdentifier (since R2025a) | Specifies the custom name of the enumeration in the generated code. If the target language is C++, also specifies namespace of the enumeration in the generated code. See Specify a Custom Enumeration Name. | The default return value is"". |
getDefaultValue | Returns the default enumerated value. See Specify a Default Enumeration Value. | The default return value is the first value in the enumeration class definition. |
getDataScope (since R2025a) | Specifies whether the enumerated type is exported or imported. See: Import Enumerated Type Definition from External Header FileExport Enumerated Type Definition to External Header File | "Auto" (default) — If a nonempty header file name is specified using thegetHeaderFile method, the code generator imports the enumerated type definition from this file.Otherwise, the code generator produces the type definition either locally or in a*_types.h file."Imported" — The code generator imports the enumerated type definition from a header file that you provide. You must also provide agetHeaderFile method that returns the path to this header file as a nonempty string."Exported" — If you specified a nonempty header file name using thegetHeaderFile method, the code generator produces the enumeration definition in this file. Otherwise the code generator produces the enumeration definition in a*_types.h file. |
getHeaderFile | Specifies the header file that contains the definition of an imported or exported enumerated type. See: Import Enumerated Type Definition from External Header FileExport Enumerated Type Definition to External Header File. | The default return value is"". |
isTunableInCode (since R2025a) | For imported enumerated type, specifies whether the values of enumeration members can be modified at build time, that is, after source code generation. See Modify Enumeration Member Values at Build Time. | false (default) — You cannot modify enumeration member values at build time.true — You can modify enumeration member values at build time. |
Generate C++ Code That Contains Ordinary C Enumeration
When you generate code using a language standard that supports enumeration classes (C++11 or newer), your MATLAB enumeration class is converted to a C++ enumeration class. For example:
enum class MyEnumClass16 : short
{
Orange = 0, // Default value
Yellow,
Pink
};
To generate an ordinary C enumeration instead, provide agenerateEnumClass
method that returnsfalse
. For example:
classdef MyEnumClass16 < int16 enumeration Orange(0), Yellow(1), Pink(2) end
% particular enum opting out
methods(Static)
function y = generateEnumClass()
y = false;
end
end
end
Now the generated C++ code contains an ordinary C enumeration.
enum MyEnumClass16 : short
{
Orange = 0, // Default value
Yellow,
Pink
};
Include Class Name Prefix in Generated Enumeration Value Names
By default, the generated enumerated type value name does not include the class name prefix. For example:
enum LEDcolor
{
GREEN = 1,
RED
};
typedef enum LEDcolor LEDcolor;
To include the class name prefix, provide anaddClassNameToEnumNames
method that returnstrue
. For example:
classdef LEDcolor < int32 enumeration GREEN(1), RED(2) end
methods(Static)
function y = addClassNameToEnumNames()
y=true;
end
end
end
In the generated type definition, the enumerated value names include the class prefixLEDcolor
.
enum LEDcolor
{
LEDcolor_GREEN = 1,
LEDcolor_RED
};
typedef enum LEDcolor LEDcolor;
Note
When generating enumeration classes (C++11 and newer standards), the code generator ignores this static method.
Specify a Custom Enumeration Name
Since R2025a
You can specify a custom name for a MATLAB enumeration in the generated code that can be configured based on the target language.
Consider the case where the target language is C. Provide an implementation of thegeneratedCodeIdentifier
method that, when passed the input"C"
, returns the custom name as a string.
When the target language is C++, you can specify both a custom name and a namespace for the enumeration. Provide an implementation of thegeneratedCodeIdentifier
method that, when passed the input"C++"
, returns the custom name and namespace as a string in the format "mynamespace::myname"
.
For example, define this MATLAB enumeration in the namespacematlabNamespace
:
% Defined in file +matlabNamespace/CustomEnumName.m classdef CustomEnumName < int32 enumeration Red(0), Blue(1), Green(2) end methods(Static) function n = generatedCodeIdentifier(lang) if lang == "C++" n = "cppNamespace::MyCppEnum"; else n = "myCEnum"; end end end end
Define an entry-point function xCustomEnumName
that uses this enumeration:
function out = xCustomEnumName out = matlabNamespace.CustomEnumName.Green; end
First, generate C source code for this entry-point function.
codegen -config:lib -c xCustomEnumName -report
The generated C enumeration definition is:
enum myCEnum
{
Red = 0, /* Default value */
Blue,
Green
};
Next, generate C++ source code for this entry-point function.
codegen -lang::c++ -config:lib -c xCustomEnumName -report
The generated C++ enumeration definition is:
namespace cppNamespace {
enum class MyCppEnum : int
{
Red = 0, // Default value
Blue,
Green
};
}
Specify a Default Enumeration Value
If the value of a variable that is cast to an enumerated type does not match one of the enumerated type values:
- Generated MEX reports an error.
- Generated C/C++ code replaces the value of the variable with the enumerated type default value.
Unless you specify otherwise, the default value for an enumerated type is the first value in the enumeration class definition. To specify a different default value, add your own getDefaultValue
method to the methods section. In this example, the first enumeration member value is LEDcolor.GREEN
, but the getDefaultValue
method returns LEDcolor.RED
:
classdef LEDcolor < int32 enumeration GREEN(1), RED(2) end
methods (Static)
function y = getDefaultValue()
y = LEDcolor.RED;
end
end
end
Import Enumerated Type Definition from External Header File
To specify that an enumerated type is defined in an external header file, provide a customizedgetHeaderFile
method that returns the path to the header file as a nonempty string. This example specifies thatLEDcolor
is defined in the external filemy_LEDcolor.h
.
classdef LEDcolor < int32 enumeration GREEN(1), RED(2) end
methods(Static)
function y = getHeaderFile()
y = "my_LEDcolor.h";
end
end
end
In this case, the code generator does not produce a definition for the enumeration. You must provide the my_LEDcolor.h
file that supplies this definition. For example:
enum LEDcolor
{
GREEN = 1,
RED
};
typedef enum LEDcolor LEDcolor;
If you place the MATLAB enumeration LEDcolor
inside the MATLAB namespace nmsp
and generate C++ code, code generation preserves the name of this enumeration and places it inside the C++ namespace nmsp
in the generated code. Therefore, in the header file that you provide, you must define this enumeration inside the namespace nmsp
.
Export Enumerated Type Definition to External Header File
Since R2025a
You can instruct the code generator to produce the definition of an enumerated type in a header file that you specify. In your MATLAB enumeration class definition, provide implementations of:
- A
getDataScope
method that returns the string"Exported"
- A
getHeaderFile
method that returns the name of the header file as a nonempty string
For example, define this MATLAB enumeration classexportedEnum
:
classdef ExportedEnum < int32 enumeration red (1) blue (2) green (3) yellow (4) end methods(Static) function out = getDataScope() out = "Exported"; end function hFile = getHeaderFile() hFile = "exportedEnumHeader.h"; end end end
Define an entry-point function xExportedEnum
that uses this enumeration:
function out = xExportedEnum(in) t = local(in); out = int32(t); end
function out = local(in) t = ExportedEnum.green; if (in > 9) out = t; else out = ExportedEnum.red; end end
Generate C++ source code forxExportedEnum
:
codegen -lang:c++ -config:lib -c xExportedEnum -args 0 -report
Inspect the generated files. The C++ enumeration classExportedEnum
is defined in the header fileexportedEnumHeader.h
.
Modify Enumeration Member Values at Build Time
Since R2025a
When you specify an enumeration as imported (see Import Enumerated Type Definition from External Header File), the code generator does not produce a definition for this enumeration in the generated C/C++ source files. When you build the generated source code, you must provide a header file that contains this definition.
In the general situation, the enumeration member values in your header file must match those in your MATLAB enumeration class definition. This is because, the code generator, when attempting to optimize the generated code by performing constant-folding, might hardcode the MATLAB enumeration member values in the generated source files.
However, you can indicate that you want to modify the imported enumeration member values in your custom header file when you build the generated code. In your MATLAB enumeration class definition, provide an implementation of theisTunableInCode
static method that returnstrue
. This return value instructs the code generator to not constant-fold expressions that involve the enumeration members and retain references to the original enumeration members themselves. This behavior allows the final build artifact (MEX, library, or executable) to perform computations that use the enumeration member values provided in your current header file.
For example, consider this MATLAB enumeration class definition that is specified as both imported and tunable:
classdef Colors < int32
enumeration
Red(0),
Blue(1),
Green(2)
end
methods(Static)
function y = getHeaderFile()
y = 'Header.h'; % making this imported
end
function y = isTunableInCode()
y = true; % making this tunable
end
end
end
Define an entry-point function that uses the Colors
enumeration:
function out = xColors t = 2; if (t == Colors.Green) out = 1; elseif (t == Colors.Red) out = 2; else out = 6; end end
Generate C++ source code forxColors
:
codegen -lang:c++ -c -config:lib xColors -report
Inspect the generated xColors
entry-point function. The generated file retains all instances of the enumeration members themselves:
double xColors()
{
double out;
if (static_cast<int>(Colors::Green) == 2) {
out = 1.0;
} else if (static_cast<int>(Colors::Red) == 2) {
out = 2.0;
} else {
out = 6.0;
}
return out;
}
Now comment out the isTunableInCode
method in the enumeration and regenerate code. The code generator has now constant-folded the enumeration members and further optimized the generated code to reduce it to a single line.
double xColors()
{
return 1.0;
}
This example also highlights the fact that specifying an enumeration as tunable might prevent further optimizations of the generated code that depend on the constant-folding optimization.
Constant Conditional Expressions and Unreachable Code
To generate a static library for xColors
, create a fileHeader.h
that contains this C++ enum class definition:
enum class Colors : int
{
Green = 0, // Default value
Blue,
Red
};
To generate code and build a static library, run this command:
codegen -lang:c++ -config:lib xColors -report
Warning: C++ Compiler produced warnings. See the build log for further details. Code generation successful (with warnings): View report
For a given implementation of the Colors
enumeration, conditional expressions like static_cast<int>(Colors::Green) == 2
are constants and cause the C/C++ compiler to throw this warning:
warning C4127: conditional expression is constant
In addition, this code pattern might cause certain branches of the conditional block to become unreachable. For example, for the current definition of Colors
, the else
branch in the generated xColors
function is unreachable.
Constant conditional expressions and unreachable branches cause the generated code for tunable enumerations to violate certain coding standard rules including MISRA™ C:2012 Rules 2.1 and 14.3, and MISRA C++:2008 Rule 0-1-1.