Documentation

Control Names of Enumerated Type Values in Generated Code

This example shows how to control whether generated enumerated type value names include the class name prefix from the enumerated type definition. By default, the generated enumerated type value name does not include the class name prefix.

  1. Define the enumerated type sysMode. Store it in sysMode.m on the MATLAB® path.

    classdef(Enumeration) sysMode < int32
      enumeration
        OFF(0),
        ON(1)
      end
    end
  2. Define the enumerated type LEDcolor. Store it in LEDcolor.m on the MATLAB path.

    classdef(Enumeration) LEDcolor < int32
        enumeration
            GREEN(1),
            RED(2)
        end
     end
  3. Define the function displayState, which uses enumerated data to activate an LED display, based on the state of a device. displayState lights a green LED display to indicate the ON state and lights a red LED display to indicate the OFF state. Store in displayState.m on the MATLAB path.

    function led = displayState(state)
    %#codegen
    
    if state == sysMode.ON
        led = LEDcolor.GREEN;
    else
        led = LEDcolor.RED;
    end
  4. Generate a library for the function displayState that takes one input of enumerated data type sysMode.

    codegen -config:lib -report  displayState -args {sysMode.ON}

    codegen generates a C static library with the default name, displayState, and supporting files in the default folder, codegen/lib/displayState.

  5. Click the View Report link.

  6. In the report, on the C Code tab, click the link to the displayState_types.h file.

    The report displays the header file containing the enumerated data type definition.

    enum LEDcolor
    {
        GREEN = 1,
        RED
    };
    
    typedef enum LEDcolor LEDcolor;
    

    The enumerated value names do not include the class name prefix LEDcolor_.

  7. Modify the definition of LEDcolor to add the addClassNameToEnumNames method. Set the return value to true so that the enumerated value names in the generated code contain the class prefix.

    classdef(Enumeration) LEDcolor < int32
        enumeration
            GREEN(1),
            RED(2)
        end
    
        methods(Static)
          function y=addClassNameToEnumNames()
            y=true;
          end
        end
    end
  8. Clear existing class instances.

    clear classes
  9. Generate code.

    codegen -config:lib -report  displayState -args {sysMode.ON}
  10. Open the code generation report and look at the enumerated type definition in displayState_types.h.

    enum LEDcolor
    {
        LEDcolor_GREEN = 1,
        LEDcolor_RED
    };
    
    typedef enum LEDcolor LEDcolor;

    The enumerated value names include the class name prefix.

Was this topic helpful?