Main Content

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 run codegen, 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

  1. Define and initialize a global structure g.

  2. Use coder.cstructname to create a type object T that has the properties of g and names the generated C structure type mytype.

  3. Generate code for getmyfield, specifying that g is a global variable with the type T.

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

  1. Open the MATLAB Coder app and specify that you want to generate code for getmyfields.

  2. On the Define Input Types page, Click Add global.

  3. Click the field next to the global variable g. Then, click Define Initial Value.

  4. Enter struct('a',5).

  5. To specify the C structure type name to use for g, click the gear icon.

  6. 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.

See Also

Related Topics