Name C Structure Type to Use with Global Structure Variable
This example shows how to name the C structure type to use in code generated for a global structure at the command line.
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, use coder.cstructname
to create a type object that names the C structure type. When you run codegen
, specify that the global variable has that type. You can also use this approach to name the C structure type for a global cell array.
Alternatively, you can name the C structure type of a global structure variable by using the MATLAB® Coder™ app. In the app, after you define a global structure variable, click the Type Name button in the variable definition and enter the C structure type name. See Define Global Variables in the MATLAB Coder App.
Write a MATLAB Function That Uses a Global Variable
Write a MATLAB® function named getmyfield
that returns field f1
, which is a field of global structure variable g
.
type getmyfield
function y = getmyfield %#codegen global g; y = g.f1; end
Specify the C Structure Type Name
Define and initialize the global structure g
. Then, use coder.cstructname
to create a type object named T
that has the properties of g
and names the generated C structure type myStructType
.
global g g = struct("f1",5)
g = struct with fields:
f1: 5
T = coder.cstructname(g,"myStructType")
T = coder.StructType 1×1 myStructType struct f1: 1×1 double Edit Type Object
Generate Code Using the C Structure Type
Generate code for getmyfield
, specifying that g
is a global variable with the type T
. Inspect the C structure type definition in the generated code. The name of the generated C structure type is myStructType
.
codegen -config:lib -globals {"g",T} getmyfield
Code generation successful.
file = fullfile("codegen","lib","getmyfield","getmyfield_types.h"); coder.example.extractLines(file,"/* Type Definitions */","#endif",1,1)
/* Type Definitions */ #ifndef typedef_myStructType #define typedef_myStructType typedef struct { double f1; } myStructType; #endif /* typedef_myStructType */