Name the C Structure Type to Use with a Global Structure Variable
This example shows how to name the C structure type to use in code generated for a global structure.
To name the C structure type to use for a structure variable, you use coder.cstructname
. However, you cannot apply coder.cstructname
directly to a global variable inside a function. Instead, specify the C structure type name in one of these ways:
At the command line, use
coder.cstructname
to create a type object that names the C structure type. When you runcodegen
, specify that the global variable has that type.In the MATLAB® Coder™ app, after you define and initialize a global variable, specify the C structure type name in the structure properties dialog box.
You can also use these approaches to name the C structure type for a global cell array.
Write a MATLAB Function That Uses a Global Variable
Write a MATLAB® function getmyfield
that returns field a
of global variable g
.
type getmyfield
function y = getmyfield() % Copyright 2018 The MathWorks, Inc. %#codegen global g; y = g.a; end
Specify the C Structure Type Name at the Command Line
Define and initialize a global structure
g
.Use
coder.cstructname
to create a type objectT
that has the properties ofg
and names the generated C structure typemytype
.Generate code for
getmyfield
, specifying thatg
is a global variable with the typeT
.
global g g = struct('a',5); T = coder.cstructname(g,'mytype'); codegen -config:lib -globals {'g',T} getmyfield
Code generation successful.
In the generated code, g
has the type mytype
.
mytype g;
The generated C structure type mytype
is:
typedef struct { double a; } mytype;
Specify the C Structure Type Name in the MATLAB Coder App
Open the MATLAB Coder app and specify that you want to generate code for
getmyfields
.On the Define Input Types page, Click Add global.
Click the field next to the global variable
g
. Then, clickDefine Initial Value
.Enter
struct('a',5)
.To specify the C structure type name to use for
g
, click the gear icon.In the Properties dialog box, next to C type definition name, enter
mytype
.
Alternatively, if you defined g
or a type object for g
in the workspace, you can enter g
or the type object as the initial value.