Define Global Variables in the MATLAB Coder App - MATLAB & Simulink (original) (raw)

Main Content

You must define a type and initial value for each global variable that you use in your MATLAB® code before you generate C/C++ code. If you do not define global variables at the time of code generation by using the MATLAB Coder™ app, the app looks for the variable in the MATLAB global workspace. If the variable does not exist, the app generates an error.

Add and Rename Global Variables

To add a global variable in the MATLAB Coder app, on the Entry Points pane, click New entry point > New global. The Entry Points pane displays a Globals section. To add additional global variables, click the New global button.

For example, this image shows the Entry Points pane for the entry-point function use_globals with two global variables. Because the global variable types are not defined, the app displays an error icon.

Entry Points pane showing undefined global variables

The MATLAB Coder app uses default names for the global variable you add. To rename a variable, click the variable and enter a new name.

Define Global Variable Type

To define the types and initial values for global variables, use one of these methods:

For example, this image shows global variables A andB, which are defined as a 3-by-4 array of doubles and a 1-by-3 array of doubles, respectively. The app displays a warning icon because these variables lack initial values.

Globals section showing global variables with type definitions

Specify Initial Value

Specify an initial value for a global variable value by using MATLAB code or by loading the variable from an existing MAT file. Point to a variable in the Globals section, then click the Modes and Actions button . In the Modes section, selectSet initial value.

For example, this image shows global variables A andB after you set the initial values.

Globals section showing global variables with type definitions and initial values

The code generator evaluates and defines initial values at code generation time. If you change the value of the source variable in the MAT file or if the result of the MATLAB command changes after code generation, the initial value of the global variable does not update in the generated code.

If you specify an initial value that has a different type than the one you specify for the global variable, the app updates the variable type to match the initial value.

See Also

MATLAB Coder | codegen

Topics