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. In the Simulink.Parameter property dialog box, 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 Model Data Editor, on the Parameters tab, click the Show/refresh additional information button.

2. Set the Change view drop-down list to Code.

3. Use the Storage Class column to change the storage class of myParam from Define to ImportedDefine.

4. For myParam, set Header File to external_params.h. The generated code imports the macro definition from a custom header file named external_params.h.

5. 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 */

7. 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 includes (#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.

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

Related Topics