Main Content

Access Custom C++ Code in Stateflow Charts

You can integrate custom code written in C or C++ with Stateflow® charts in Simulink® models. By sharing data and functions between your custom code and your Stateflow chart, you can augment the capabilities of Stateflow and take advantage of your preexisting code. For more information, see Reuse Custom Code in Stateflow Charts.

Task 1: Prepare Code Files

Prepare your custom C++ code for simulation as follows:

  1. Add a C function wrapper to your custom code. This wrapper function executes the C++ code that you are including.

    The C function wrapper should have this form:

    int my_c_function_wrapper()
    	//C++ code
    	return result;
  2. Create a header file that prototypes the C function wrapper in the previous step.

    The header file should have this form:

    int my_c_function_wrapper();

    The value _cplusplus exists if your compiler supports C++ code. The extern "C" wrapper specifies C linkage with no name mangling.

Task 2: Include Custom C++ Source and Header Files for Simulation

To include custom C++ code for simulation, you must configure your simulation target and select C++ as the custom code language:

  1. Open the Model Configuration Parameters dialog box.

  2. In the Model Configuration Parameters dialog box, select the Simulation Target pane.

  3. Add your custom header file in the Header file subpane. Click Apply.

  4. Add your custom C++ files in the Source files subpane. Click Apply.

  5. In the Model Configuration Parameters dialog box, select the Code Generation pane.

  6. Select C++ from the Language menu.

  7. Click OK.

Task 3: Choose a C++ Compiler

You can change the default compiler by calling the mex –setup command, and following the instructions. For a list of supported compilers, see

Task 4: Simulate the Model

Simulate your model by clicking the play button in the toolbar of the editor.

For information on setting simulation options using the command-line API, see Set Simulation Parameters Programmatically.

Related Topics