Documentation

Function Reuse in Generated Code

This model shows how to configure a subsystem for code reuse. To specify that a subystem's code executes as an atomic unit, select the Treat as atomic unit parameter on the block parameters dialog box. This parameter enables the Function Packaging parameter of the Code Generation tab. The Function Packaging Parameter has these four settings:

  • Inline: An inlined function

  • Nonreusable function: Function with I/O passed as global data

  • Reusable function: Function with I/O passed as function arguments

  • Auto: Let Simulink Coder optimize based on context

The Reusable function and Auto settings permit the code generator to reuse subystem code. The Reusable function and Nonreusable function settings enable the Function name options, Function name, and File name options parameters.

Example Model

The rtwdemo_ssreuse model contains two identical subsystems, SS1 and SS2. For these subsystems, the Function packaging parameter is set to Reusable function, and the Function name parameter is myfun. The subsystems are parameterized masked subsystems. To see the contents of the masked subsystems, right-click the subsystem blocks and select Mask > Look Under Mask.

model = 'rtwdemo_ssreuse';
open_system(model);

Generate Code

Create a temporary folder for the build and inspection process.

currentDir=pwd;
[~,cgDir]=rtwdemodir();

Build the model.

rtwbuild(model)
### Starting build procedure for model: rtwdemo_ssreuse
### Successful completion of build procedure for model: rtwdemo_ssreuse
cfile=fullfile(cgDir, 'rtwdemo_ssreuse_grt_rtw', 'rtwdemo_ssreuse.c');
rtwdemodbtype(cfile, '/* Model step', '/* Model initialize', 1, 0);
/* Model step function */
void rtwdemo_ssreuse_step(void)
{
  /* Outputs for Atomic SubSystem: '<Root>/SS1' */

  /* Inport: '<Root>/In1' incorporates:
   *  Inport: '<Root>/In2'
   */
  myfun(rtwdemo_ssreuse_U.In1, rtwdemo_ssreuse_U.In2, &rtwdemo_ssreuse_B.SS1,
        rtwdemo_ssreuse_P.T1Data, rtwdemo_ssreuse_P.T1Break);

  /* End of Outputs for SubSystem: '<Root>/SS1' */

  /* Outport: '<Root>/Out1' */
  rtwdemo_ssreuse_Y.Out1 = rtwdemo_ssreuse_B.SS1.LookupTable;

  /* Outputs for Atomic SubSystem: '<Root>/SS2' */

  /* Inport: '<Root>/In1' incorporates:
   *  Inport: '<Root>/In2'
   */
  myfun(rtwdemo_ssreuse_U.In1, rtwdemo_ssreuse_U.In2, &rtwdemo_ssreuse_B.SS2,
        rtwdemo_ssreuse_P.T2Data, rtwdemo_ssreuse_P.T2Break);

  /* End of Outputs for SubSystem: '<Root>/SS2' */

  /* Outport: '<Root>/Out2' */
  rtwdemo_ssreuse_Y.Out2 = rtwdemo_ssreuse_B.SS2.LookupTable;
}

In the model step function, there are two calls to the reusable function, myfun. The mask parameters, T1Break, T1Data, T2Break, and T2Data, are function arguments.

Close the model and clean up.

bdclose(model)
rtwdemoclean;
cd(currentDir)
Was this topic helpful?