Generate Code for Global Data
Workflow
To generate C/C++ code from MATLAB® code that uses global data:
Declare the variables as global in your code.
Before using the global data, define and initialize it.
For more information, see Define Global Data.
Generate code using the MATLAB Coder™ app or using
codegen
.
If you use global data, you must also specify whether you want to synchronize this data between MATLAB and the generated MEX function. For more information, see Synchronizing Global Data with MATLAB.
Declare Global Variables
When using global data, you must first declare the global variables in your
MATLAB code. Consider the use_globals
function that uses two
global variables AR
and
B
:
function y = use_globals(u) %#codegen % Turn off inlining to make % generated code easier to read coder.inline('never'); % Declare AR and B as global variables global AR; global B; AR(1) = u + B(1); y = AR * 2;
Define Global Data
You can define global data in the MATLAB global workspace, in a MATLAB Coder project, or at the command line. If you do not initialize global data in the project or at the command line, MATLAB Coder looks for the variable in the MATLAB global workspace. If the variable does not exist, MATLAB Coder generates an error.
Defining Global Data in the MATLAB Global Workspace
To generate a MEX function for the use_globals
function
described in Declare Global Variables using
codegen
:
In the MATLAB workspace, define and initialize the global data. At the MATLAB prompt, enter:
global AR B; AR = ones(4); B = [1 2 3];
Generate a MEX file.
codegen use_globals -args {0} % Use the -args option to specify that the input u % is a real, scalar, double % By default, codegen generates a MEX function, % use_globals_mex, in the current folder
Defining Global Data Using the MATLAB Coder App
On the Define Input Types page, automatically define input types or click Let me enter input or global types directly.
The app displays a table of entry-point inputs.
To add a global variable, click Add global.
By default, the app names the first global variable in a project
g
, and subsequent global variablesg1
,g2
, and so on.Under Global variables, enter a name for the global variable.
Click the field to the right of the global variables name. Specify the type and initial value of the global variable. See Specify Global Variable Type and Initial Value Using the App.
If you do not specify the type, you must create a variable with the same name in the global workspace.
Defining Global Data at the Command Line
To define global data at the command line, use the codegen
-globals
option. For example, to compile the
use_globals
function described in Declare Global Variables, specify two global inputs
AR
and B
at the command line. Use the
-args
option to specify that the input u
is
a real, scalar double. By default, codegen generates a MEX function,
use_globals_mex
, in the current
folder.
codegen -globals {'AR',ones(4),'B',[1 2 3]} use_globals -args {0}
Alternatively, specify the type and initial value with the
-globals
flag using the format -globals {'g', {type,
initial_value}}
. For cell arrays, you must use this format. See Specify Global Cell Arrays at the Command Line.
Defining Variable-Size Global Data. To provide initial values for variable-size global data, specify the type and
initial value with the -globals
flag using the format
-globals {'g', {type, initial_value}}
. For example, to
specify a global variable g1
that has an initial value
[1 1]
and upper bound [2 2]
,
enter:
codegen foo -globals {'g1', {coder.typeof(0, [2 2],1),[1 1]}}
coder.typeof
.Synchronizing Global Data with MATLAB
Why Synchronize Global Data?
The generated MEX function and MATLAB each have their own copies of global data. To make these copies consistent, you must synchronize their global data whenever the two interact. If you do not synchronize the data, their global variables might differ. The level of interaction determines when to synchronize global data. For more information, see When to Synchronize Global Data.
When global data is constant, you cannot synchronize the global data with MATLAB. By default, the MEX function tests for consistency between the compile-time constant global values and the MATLAB values at function entry and after extrinsic function calls. If the MATLAB values differ from the compile-time constant global values, the MEX function ends with an error. For information about controlling when the MEX function tests for consistency between the compile-time constant global values and the MATLAB values, see Consistency Between MATLAB and Constant Global Data.
When to Synchronize Global Data
By default, synchronization between the MEX function's global data and MATLAB occurs at MEX function entry and exit and for extrinsic calls. Use this synchronization method for maximum consistency between the MEX function and MATLAB.
To improve performance, you can:
Select to synchronize only at MEX function entry and exit points.
Disable synchronization when the global data does not interact.
Choose whether to synchronize before and after each extrinsic call.
The following table summarizes which global data synchronization options to use. To learn how to set these options, see How to Synchronize Global Data.
Global Data Synchronization Options
If you want to | Set the global data synchronization mode to: | Synchronize before and after extrinsic calls? |
---|---|---|
Have maximum consistency when all extrinsic calls modify global data. | At MEX-function entry, exit and extrinsic
calls (default) | Yes. Default behavior. |
Have maximum consistency when most extrinsic calls modify global data, but a few do not. | At MEX-function entry, exit and extrinsic
calls (default) | Yes. Use the |
Have maximum consistency when most extrinsic calls do not modify global data, but a few do. | At MEX-function entry and exit | Yes. Use the |
Maximize performance when synchronizing global data, and none of your extrinsic calls modify global data. | At MEX-function entry and exit | No. |
Communicate between generated MEX functions only. No interaction between MATLAB and MEX function global data. | Disabled | No. |
How to Synchronize Global Data
To control global data synchronization, set the global data synchronization mode and select whether to synchronize extrinsic functions. For guidelines on which options to use, see When to Synchronize Global Data.
You can control the global data synchronization mode from the project settings
dialog box, the command line, or a MEX configuration dialog box. You control the
synchronization of data with extrinsic functions using the
coder.extrinsic
-sync:on
and -sync:off
options.
Controlling the Global Data Synchronization Mode Using the MATLAB Coder App
To open the Generate dialog box, on the Generate Code page, click the Generate arrow .
Set Build type to
MEX
.Click More Settings.
On the Memory tab, set Global data synchronization mode to
At MEX-function entry and exit
orDisabled
, as applicable.
Controlling the Global Data Synchronization Mode from the Command Line
In the MATLAB workspace, define the code generation configuration object. At the MATLAB command line, enter:
mexcfg = coder.config('mex');
At the MATLAB command line, set the
GlobalDataSyncMethod
property toSyncAtEntryAndExits
orNoSync
, as applicable. For example:mexcfg.GlobalDataSyncMethod = 'SyncAtEntryAndExits';
When compiling your code, use the
mexcfg
configuration object. For example, to generate a MEX function for functionfoo
that has no inputs:codegen -config mexcfg foo
Controlling Synchronization for Extrinsic Function Calls. To control whether synchronization between MATLAB and MEX function global data occurs before and after you call an
extrinsic function, use the
coder.extrinsic
-sync:on
and
-sync:off
options.
By default, global data is:
Synchronized before and after each extrinsic call, if the global data synchronization mode is
At MEX-function entry, exit and extrinsic calls
. If you are sure that certain extrinsic calls do not change global data, turn off synchronization for these calls using the-sync:off
option. For example, if functionsfoo1
andfoo2
do not change global data, turn off synchronization for these functions:coder.extrinsic('-sync:off', 'foo1', 'foo2');
Not synchronized, if the global data synchronization mode is
At MEX-function entry and exit
. If the code has a few extrinsic calls that change global data, turn on synchronization for these calls using the-sync:on
option. For example, if functionsfoo1
andfoo2
change global data, turn on synchronization for these functions:coder.extrinsic('-sync:on', 'foo1', 'foo2');
Not synchronized, if the global data synchronization mode is
Disabled
. When synchronization is disabled, you cannot use the-sync:on
option to control the synchronization for specific extrinsic calls.
Clear Global Data
Because MEX functions and MATLAB each have their own copies of global data, you must
clear
both copies to ensure
that consecutive MEX runs produce the same results. The clear
global
command removes only the copy of the global data in the
MATLAB workspace. To remove both copies of the data, use the clear
global
and clear mex
commands together. The
clear all
command also removes both copies.
Define Constant Global Data
If you know that the value of a global variable does not change at run time, you can reduce overhead in the generated code by specifying that the global variable has a constant value. You cannot write to the constant global variable.
Define Constant Global Data Using the MATLAB Coder App
On the Define Input Types page, automatically define input types or click Let me enter input or global types directly.
The app displays a table of entry-point inputs.
To add a global variable, click Add global.
By default, the app names the first global variable in a project
g
, and subsequent global variablesg1
,g2
, and so on.Under Global Variables, enter a name for the global variable.
Click the field to the right of the global variable name.
Select
Define Constant Value
.In the field to the right of the global variable, enter a MATLAB expression.
Define Constant Global Data at the Command Line
To specify that a global variable is constant using the codegen
command, use the -globals
option with the coder.Constant
class.
Define a configuration object for the code generation output type that you want. For example, define a configuration object for MEX code generation:
cfg = coder.config('mex');
Use
coder.Constant
to specify that a global variable has a constant value. For example, the following code specifies that the global variableg
has initial value4
and that global variablegc
has the constant value42
.global_values = {'g', 4, 'gc', coder.Constant(42)};
Generate the code using the
-globals
option. For example, generate code formyfunction
specifying that the global variables are defined in the cell arrayglobal_values
.codegen -config cfg -globals global_values myfunction
Consistency Between MATLAB and Constant Global Data
By default, the generated MEX function verifies that the values of constant global
data in the MATLAB workspace are consistent with the compile-time values in the generated
MEX. It tests for consistency at function entry and after calls to extrinsic
functions. If the MEX function detects an inconsistency, it ends with an error. To
control when the MEX function tests for consistency, use the global synchronization
mode and the coder.extrinsic
synchronization options.
The following table shows how the global data synchronization mode and the
coder.extrinsic
synchronization option setting determine when
a MEX function verifies consistency between the compile-time constant global data
values and MATLAB.
Global Data Synchronization Mode (Project) | GlobalDataSyncMethod (MEX Configuration Object) | Verify Consistency of Constant Global Values at MEX Function Entry | coder.extrinsic synchronization option | Verify Consistency of Constant Global Values After Extrinsic Function Call |
---|---|---|---|---|
|
| yes |
| yes |
| no | |||
|
| yes |
| yes |
| no | |||
|
| no | N/A | N/A |
Constant Global Data in a Code Generation Report
The code generation report provides the following information about a constant global variable:
Type of
Global
on the Variables tab.Highlighted variable name in the Function pane.
Global Data Limitations for Generated Code
Global structure variables cannot contain handle objects or sparse arrays.
You cannot apply
coder.cstructname
directly to a global variable. To name the structure type to use with a global variable, usecoder.cstructname
to create a type object that names the structure type. Then, when you runcodegen
, specify that the global variable has that type. See Name the C Structure Type to Use with a Global Structure Variable.Global variables are not synchronized when there is a run-time error during SIL or PIL execution. Consider the function
SILtest
, which increments global variableg
and then produces a run-time error.In MATLAB and MEX execution,function SILtest global g; g = g + 1; error('MyError'); end
SILtest
increments and synchronizes global variableg
in the workspace. However, in SIL execution, global variableg
is not incremented in the workspace due to the run-time error.