Main Content

Macro Definitions (#define)

C Construct

#define myParam 9.8;

Export Generated Macro Definition

1. Open example model ex_param_macro.

2. In the model, select the Gain block. In the Property Inspector, set the value of the Gain parameter to myParam.

3. Next to the parameter value, click the action button (the button with three vertical dots) and select Create.

4. In the Create New Data dialog box, set Value to Simulink.Parameter(9.8). Click Create. A Simulink.Parameter object, myParam, appears in the base workspace. The Gain block uses the object to set the value of the Gain parameter, in this case, 9.8.

5. On the Code Generation tab, click the Configure in Coder App button. In the Code Mappings editor, set Storage Class to Define. Click OK.

6. To build the model and generate code, press Ctrl+B.

The generated header file ex_param_macro.h defines myParam as a macro.

/* Definition for custom storage class: Define */
#define myParam                        9.8                       /* Referenced by: '<Root>/Gain' */

Reuse Macro from Handwritten Code

1. In the Code Mappings editor, on the Parameters tab, click the Update Code Mappings button.

2. Change Storage Class of myParam from Define to ImportedDefine.

3. In the Property Inspector, under Code section, set Header File to external_params.h. The generated code imports the macro definition from a custom header file named external_params.h.

4. In your current folder, create the C header file external_params.h, which contains the #define statement.

#ifndef _EXTERNAL_PARAMS
#define _EXTERNAL_PARAMS

#define myParam 9.8

#endif

/* EOF */

5. To build the model and generate code, press Ctrl+B.

The generated header file ex_param_macro.h does not define the macro. Instead, the file uses #include to include the custom header file external_params.h.

/* Includes for objects with custom storage classes */
#include "external_params.h"

The source file ex_param_macro.c contains a guard to check that a definition for myParam exists.

#include "rtwtypes.h"
#include "external_params.h"

/*
 * Check that imported macros with storage class "ImportedDefine" are defined
 */
#ifndef myParam
#error The value of parameter "myParam" is not defined
#endif

Related Topics