Main Content

Configure C Code Generation for Model Entry-Point Functions

What Is an Entry-Point Function?

An entry point is a location in code where a transfer of program control (execution) occurs. The main function (main()) is the entry point to a C/C++ program and is called when the application starts executing. Calls to other functions, for example from the main function, provide entry points to function code. Program control is transferred to the called function. The function code executes, and when finished, returns control to the main or other calling function.

When producing code for a model, the code generator defines a set of entry-point functions that you can call to execute the generated code. You can call the generated functions from external code or from a version of the generated main function that you modify.

The Code Interface Report section of the code generation report lists the entry-point functions that the code generator produces for a model. For more information, see Analyze the Generated Code Interface.

Types of Generated Entry-Point Functions

The code generator produces entry-point functions for these types of model functions.

Type of Model FunctionModel Source NameDefault Generated Function NameDescription
Exported function (requires Embedded Coder®)ExportedFunction:slIdentifier, where slIdentifier is the name of the function-call Inport block in the modelfunction-call-inport-block-name or signal-label (if specified)For an exported-function model, the exported function for a subsystem.
Initialize functionInitializemodel_initialize

Initialization code for a model. At the start of the application code, call the function once. Do not use this function to reset the real-time model data structure (rtM).

Partition functionPartition:slIdentifier, where slIdentifier is a partition that was created explicitly from a block in the model and shown in the Simulink® Schedule Editor (for example, P1)model_stepn, where n uniquely identifies the function generated for one of the model sample periodsFor a model partition, output and update code. Model configuration parameter Single output/update function is selected (the default).
Partition update functionPartitionUpdate:slIdentifier, where slIdentifier is a partition that was created explicitly from a block in the model and shown in the Simulink® Schedule Editor (for example, P1)model_outputn and model_updaten, where n uniquely identifies the function generated for one of the model sample periodsFor a model partition, output and update code in separate functions. Model configuration parameter Single output/update function is cleared.
Periodic multitasking functionPeriodic:slIdentifier, where slIdentifier is an annotation that corresponds to the sample time period for a periodic or continuous rate of a multitasking model (for example, D1)model_stepn, where n uniquely identifies the function generated for one of the model sample periodsFor blocks in a rate-based model configured for multitasking, output and update code. The code generator produces a function for each sample period. Model configuration parameter Single output/update function is selected (the default).
Periodic multitasking update functionPeriodicUpdate:slIdentifier, where slIdentifier is an annotation that corresponds to the sample time period for a periodic or continuous rate of a multitasking model (for example, D1)model_outputn and model_updaten, where n uniquely identifies the function generated for one of the model sample periodsFor blocks in a rate-based model configured for multitasking, output and update code in separate functions. The code generator produces output and update functions for each sample period. Model configuration parameter Single output/update function is cleared.
Periodic single-tasking functionPeriodicmodel_stepFor blocks in a rate-based model configured for single-tasking, output and update code. Model configuration parameter Single output/update function is selected (the default).
Periodic single-tasking update functionPeriodicUpdatemodel_output and model_updateFor blocks in a rate-based model configured for single-tasking, output and update code in separate functions. Model configuration parameter Single output/update function is cleared.
Reset functionReset:slIdentifier, where slIdentifier is the name of the reset function in the modelmodel_reset-function-name

If the model includes a Reset Function block, reset code generated. To reset conditions or state, call the function from the application code.

Simulink FunctionSimulink Function:slIdentifier, where slIdentifier is the name of the Simulink Function block in the modelfunction-name for a global Simulink Function block or model_function-name for a scoped Simulink Function blockFor an exported-function model, the exported function for a Simulink Function block.
Terminate functionTerminatemodel_terminate

Code for turning off a system. For ERT-based models, you can suppress generation of this function by clearing the model configuration parameter Terminate function required (set by default).

If you have Embedded Coder software, to facilitate integration of external and generated code and achieve compliance with code standards and guidelines, you can configure how the code generator produces function interfaces from a model or subsystem.

Configure Whether Entry-Point Functions Are Reusable

By default, for top models, the code generator produces code that is not reusable or reentrant. Entry-point functions have a void-void interface. Code communicates with other code by directly accessing global data structures that reside in shared memory.

If your application requires reusable, multi-instance entry-point function code, you can configure the code generator to call each function (instance) with unique data. In this case, the code is reentrant.

You configure whether entry-point functions are reusable with the model configuration parameter Code interface packaging and related parameters. The parameter settings that you choose depend on factors such as configuration selections for the system target file, programming language, and argument interface.

Default Configurations for Single-Instance C Entry-Point Functions

By default, for GRT- and ERT-based system target files, the code generator produces single-instance C entry-point functions. The generated code:

  • Creates an execution function without arguments (void-void).

  • Allocates memory statically (at compile time) for model data structures.

The default model configuration parameter settings for configuring single-instance entry-point function code are:

Generate Reusable, Multi-Instance C Entry-Point Functions

You can configure the code generator to produce reusable entry-point functions in C for either a GRT- or ERT-based system target file. However, the function interfaces that the code generator produces by default varies. Assuming that model configuration parameter Language is set to C and Code interface packaging is set to Reusable function, the code generator produces this entry-point function code for each system target file scenario.

System Target FileInterface
GRT-based
  • Reusable, multi-instance C entry-point functions that are reentrant.

  • Packs values of model root-level Inport blocks and Output blocks into the real-time model data structure. Passes that structure to the execution function as an argument by reference.

  • Allocates memory dynamically at runtime for the data of a model instance. Allocates the memory by calling a function, such as malloc.

ERT-based
  • Reusable, multi-instance C entry-point functions that are reentrant.

  • Passes the value of each model root-level Inport block and Outport block to the execution function as a separate argument.

  • Allocates memory statically for model data structures.

If you are using an ERT-based system target file and want to generate reusable, multi-instance C entry-point functions that are reentrant, consider:

  • Using dynamic memory allocation to initialize model data structures. Select Use dynamic memory allocation for model initialization.

  • Packing values of model root-level Inport blocks into a structure, packing values of root-level Outport blocks into a second structure, and passing the structures to the execution function as arguments by reference. Set Pass root-level I/O as to Structure reference.

  • Packing values of model root-level Inport blocks and Output blocks into the real-time model data structure and passing that structure to the execution function as an argument by reference. Set Pass root-level I/O as to Part of model data structure.

Generate Reusable, Multi-Instance C++ Entry-Point Functions

The C++ class interface encapsulates model data as class properties and entry-point functions as class methods. That interface is available for use with ERT-based system target files. To use the interface, set Language to C++ and set Code interface packaging to C++ class. You can:

  • Preview and customize the C++ class interface by clicking Configure C++ Class Interface. Customization means that you can generate code for integration with external code and verify that the code complies with coding standards.

  • Configure the visibility of class inheritance by specifying whether to generate the block parameter structure as a public, private, or protected data member. Set Parameter visibility to public, private, or protected.

  • Generate C++ interface code for model block parameters that meet code execution speed or tunability requirements. The code can be noninlined or inlined access methods. Set Parameter access to Method or Inlined method.

  • Generate C++ interface code for model root-level Inport and Outport blockset that meets code execution speed, data tunability, or data packaging requirements. The code can be one of these types of access methods.

    For Access Method TypeSet External I/O access To
    NoninlinedMethod
    InlinedInlined method
    Noninlined structure-basedStructure-based method
    Inlined structured-basedInlined structure-based method
  • Configure the visibility of class inheritance by specifying whether to generate the root-level I/O structure as a public, private, or protected data member. Set External I/O visibility to public, private, or protected.

Choose an Approach for Configuring Generated C Function Interfaces

To facilitate integration of external and generated code and achieve compliance with code standards and guidelines, you can use the Code Mappings editor or code mappings API to configure how the code generator produces function interfaces from a model or subsystem.

ConfigurationMore Information
Default naming rules for categories of functions (initialize/terminate, execution, and shared utility) across a modelConfigure Default Code Generation for Functions
Name for individual entry-point functions (override the default naming rule)Configure Names for Individual C Entry-Point Functions
Step function interface (function name, return value, and argument C type qualifiers, names, and order) for the base rate step entry-point function interactivelyConfigure Name and Arguments for Individual Step Functions
Function interfaces (function name, return value, and argument C type qualifiers, names, and order) for Simulink Function and Function Caller blocks interactivelyConfigure Entry-Point Function Interfaces for Simulink Function and Function Caller Blocks

You can use software-in-the-loop (SIL) testing to verify code generated for customized entry-point functions. Create a SIL block by using your generated code. Then, integrate the SIL block into a model to verify that the generated code provides the same result as the original model or nonvirtual subsystem. For more information, see Choose a SIL or PIL Approach.

Configure Default Code Generation Settings for a Function Category

Reduce the effort of preparing a model for C code generation by specifying default configurations for categories of functions across a model. For example, you can configure function name rules and placement of function code in memory sections. Applying default configurations can save time and reduce the risk of introducing errors in code, especially for models that have a large number functions.

The code generator produces entry-point functions for these categories of model functions:

Function CategoryDescription
Initialize/TerminateFunctions that initialize and turn off a system
ExecutionFunctions that initiate execution and resets
Shared utilityShared utility function code

Configure default code mappings for functions by using the Code Mappings Editor or code mappings API function setFunctionDefault. Using these interfaces, you can associate a function category with a function customization template defined in the model's Embedded Coder Dictionary.

If your application requires that you configure the placement of entry-point functions in memory, for example, to optimize the generated code for specific hardware, you can apply a default memory section to a category of functions across a model. In the Code Mappings editor, map a function category to a function customization template that is defined to use a specific memory section. See .

If a function customization template does not exist, you can create one by using the Embedded Coder Dictionary (see Define Storage Classes, Memory Sections, and Function Templates for Software Architecture).

For an example of how to configure default configurations for function categories, see Configure Default C Code Generation for Categories of Data Elements and Functions.

Configure Names for Individual C Entry-Point Functions

For your generated C code to adhere to code standards and guidelines or to more easily integrate that code with external code, you can configure the name of an individual entry-point function. For example, you can name the initialize function generated for a model myInitFunc.

If your model meets at least one of these criteria, consider configuring the names of functions individually:

  • Uses multiple functions that have unique naming requirements.

  • Uses few functions.

  • Has a default configuration for a function category and you need to override the configuration for a specific function.

Configure function names for individual step functions by using the Code Mappings editor or code mappings API function setFunction. Using these interfaces, you can associate a function with a function customization template that is defined in the model's Embedded Coder Dictionary and specify a function name.

This example shows how to change the name of the initialize function for model rtwdemo_fcnprotoctrl.

  1. Open and save a copy of model rtwdemo_fcnprotoctrl in a writable location.

  2. Open the Embedded Coder app.

  3. On the C Code tab, select Code Interface > Individual Element Code Mappings.

  4. In the Code Mappings editor, Functions tab, change the function name by using one of these methods:

    • In the Function Name column, enter a name for the function.

    • In the Function Preview column, click the function prototype hyperlink to open a configuration dialog box. In the C Initialize Function Name field, enter the function name. Click Apply to verify the change in the C function prototype field or click OK to exit the dialog box and view the function name in the Function Preview column of the Code Mappings editor.

    For this example, change the name of the initialize function to fcnprotoctrl_init.

  5. Save the model.

  6. Generate code.

  7. Verify the changes in the generated code. In the Code view, find instances of function name fcnprotoctrl_init. The function name appears in generated files rtwdemo_fcnprotoctrl.h and rtwdemo_fcnprotoctrl.c.

    • In rtwdemo_fcnprotoctrl.h:

      extern void fcnprotoctrl_init(void);
      
    • In rtwdemo_fcnprotoctrl.c:

      void fcnprotoctrl_init(void)
      {
        ...
      }

Configure Name and Arguments for Individual Step Functions

For your generated C code to adhere to code standards and guidelines or to more easily integrate the code with external code, you can configure the name and arguments of individual step functions generated for Simulink periodic functions. You can customize these aspects of a step function:

  • Function name

  • Argument names

  • Order of the arguments

  • Return value and argument data qualifiers

  • Buffering optimizations for arguments

If your model meets at least one of these criteria, consider configuring the name and arguments of a step function individually:

  • Is a periodic, single-tasking model for which the code generator produces one step function.

  • Has a default configuration for Execution function category and you need to override the configuration for a specific step function.

Configure code mappings for individual step functions by using the Code Mappings editor or code mappings API function setFunction. Using these interfaces, you can associate a function with a function customization template that is defined in the model's Embedded Coder Dictionary and completely customize the step function prototype.

This example shows how to customize the step function name and arguments for a rate-based, single-tasking model.

Open the Configuration Dialog Box

1. Open and save a copy of model rtwdemo_fcnprotoctrl to a writable location.

2. Open the Embedded Coder app.

3. On the C Code tab, select Code Interface > Individual Element Code Mappings.

4. In the Code Mappings editor, click the Functions tab.

5. For the step function row, in the Function Preview column, click the prototype hyperlink to open the Configure C Step Function Interface dialog box.

In the Configure C Step Function Interface dialog box, the C function prototype field displays a preview of changes that you make to the function prototype.

For models configured to generate multi-instance code, see Generate Reentrant Code from Top Models.

Customize the Function Name

1. In the Configure C Step Function Interface dialog box, set C Step Function Name to fcnprotoctrl_run. The function preview is updated to reflect the new function name.

2. Click Apply, close the dialog box, and save the model.

3. Generate code and verify the name change.

  • Click the Code tab. In the Code view file list, select file rtwdemo_fcnprotoctrl.h. In the Search field, verify that the list of code elements includes function name fcnprotoctrl_run. To view the declaration, select the function name.

The declaration is highlighted in the code:

  • Verify the name change in file rtwdemo_fcnprotoctrl.c. To view the source code (definition), in the Search field, select fcnprotoctrl_run.

For more examples, see Configure Names for Individual C Entry-Point Functions.

Customize Function Arguments

Configure Global Data Structures

By default, a top or referenced model uses a void-void step function to pass data. This type of function enables generated code to communicate with external code by accessing global data stored as data structures that reside in shared memory.

To configure a model to have a void-void step function, open the Configure C Step Function Interface dialog box and clear the Configure arguments for Step function prototype check box. Verify the change in the C function prototype preview.

Configure Arguments

Rate-based model step functions can use arguments to pass data. You can customize these argument settings:

  • Return value

  • Type qualifiers

  • Names

  • Order

Example

1. Open the Configure C Step Function Interface dialog box. In the Code Mappings editor, click the Functions tab. Then, click the function preview for the step function.

2. In the Configure C Step Function Interface dialog box, select Configure arguments for Step function prototype.

3. Click Get default. The dialog box expands to show a field for configuring the function return value and a table that lists input and output arguments with default settings.

4. Customize the return value of the step function. Set C return argument to either void or one of the output arguments. For this example, select void.

5. For each argument, specify a C Type Qualifier.

Type Qualifiers:

  • Value: Value, for example, arg

  • Const: Value with the const qualifier, for example, const arg

  • Pointer to const: Value with const qualifier and referenced by pointer, for example, const *arg

  • Pointer: Reference by pointer, for example, *arg

  • Const pointer to const: Value with const qualifier, reference by pointer, and the pointer itself, for example, const *const arg

Models that include a referenced model

  • For a referenced model, the type qualifier for a root input argument in the step function interface is set to Auto. The code generator uses the interface specification by generating a type cast that discards the const qualifier from the source signal.

  • For the parent of the reference model, the type qualifier for the source signal is set to a value other than Auto. To override this behavior, add a const type qualifier to the referenced model.

For this example, make no changes to the C type qualifier.

6. Customize the argument names by editing values in the C Identifier Name column.

For this example, change the names of the arguments by removing the underscores, for example, change arg_In1 to argIn1.

7. Customize the argument order by dragging table rows to new positions.

For this example, move Out1 to the first position. Move Out 2 to the third position.

8. Validate, apply your changes, close the dialog box, and save the model.

9. Generate code and verify the changes in the Code view.

  • Verify your changes in file rtwdemo_fcnprotoctrl.h by checking that the Search field includes function fcnprotoctrl_run.To view the function declaration, select the function name.

  • Verify your changes in file rtwdemo_fcnprotoctrl.c.To view the definition for the function, select function name fcnprotoctrl_run.

Prototype Different From Preview

In the Configure C Step Function Interface dialog box, the function prototype preview for a referenced model can show fewer arguments than the function prototype in the generated code.

For example, consider a model named mdlref_counter with an inport (arg_input), an outport (arg_output), and a saturation block with limits that have workspace parameter argument names lower_saturation_limit and upper_saturation_limit. The Configure C Step Function Interface dialog box shows a function prototype preview as:

mdlref_counter_custom(arg_input, arg_output)

In the generated code, the prototype includes the parameter arguments:

mdlref_counter_custom(real_T arg_input, real_T arg_output, real_T 
  rtp_lower_saturation_limit, real_T rtp_upper_saturation_limit)

Optimize Buffering for Arguments

You can optimize the buffering required for I/O arguments in the step function for a model. If you adhere to these requirements when configuring an inport and outport pair, the code generator merges the corresponding arguments and reuses the associated buffer.

  • The Inport and Outport blocks must have the same properties, including data type, dimension, and sample rate.

  • The sample rate of the Inport and Outport blocks must be the same as the base rate of the model.

  • A conditionally executed subsystem cannot drive the Outport block.

  • A single, nonvirtual block output must drive the Outport block. For example, a Mux block, which merges multiple buffers, cannot drive the Outport block.

  • In the Configure C Step Function Interface dialog box, you must configure the Inport and Outport with the same C type qualifier and identifier name.

This example shows how to merge arguments for ports In3 and Out2 for example model rtwdemo_fcnprotoctrl.

1. Open the Configure C Step Function Interface dialog box for the model rtwdemo_fcnprotoctrl.

2. Open the display for the arguments by selecting Configure arguments for Step function prototype.

3. For ports In3 and Out2, set C Type Qualifier to Pointer and C Identifier Name to sharedArg.

4. Verify that the preview shows the merged argument for argIn3 and argOut2.

5. Validate, apply your changes, close the dialog box, and save the model.

6. Generate and view the code. In the Code view, search for the fcnprotoctrl_run function and check the function interface. For this example, the shared argument appears in read code for the Inport block and write code for the Outport block.

Configure Code Generation Settings for C Entry-Point Functions Programmatically

To automate configuration of model functions for C code generation, use the programming interface for code mappings. For example, when creating custom block libraries or part of an application test environment, use the programming interface to automate function configuration.

Typical uses of these functions include:

  • Create a function interface.

  • Modify an existing function interface.

  • Create a function interface, starting with default configuration information from a model.

  • Reset the model function interface to the default ERT function configuration.

For an example of how to configure code generation settings for C entry-point functions programmatically, see Configure Default Data and Function Code Generation Programmatically. That example shows how to configure default settings for function categories and individual functions.

How to Interface with Generated Entry-Point Functions

  1. After generating code for a model, use the Code view to review the generated entry-point functions and, if applicable, variables representing external input and output ports.

  2. Add #include statements to your external code that include the generated header files that declare the model entry-point functions.

  3. Add an #include statement that includes the generated file rtwtypes.h. This file provides type definitions, #define statements, and enumerations.

  4. Initialize target-specific data structures and hardware, such as ADCs or DACs.

  5. If applicable, initialize data for each instance of a reusable model.

  6. If applicable, write input data to generated variables that represent model Inport blocks.

  7. Call the generated entry-point functions or set up use of the rt_OneStep function.

  8. If applicable, read data from generated variables that represent model Outport blocks.

For more information, see Deploy Generated Standalone Executable Programs To Target Hardware.

C Function Interface Customization Limitations

These limitations apply to customizations for generated C function interfaces:

  • You must select the model configuration parameter Single output/update function.

  • Multirate models are supported, but you must configure the models for single tasking.

  • You must configure root-level inports and outports to use the Default storage class.

  • If you choose to customize a function interface, you must provide your own custom main program. You cannot configure the function interface with the static rt_main.c that MathWorks® provides. Specifying a function interface configuration other than the default creates a mismatch between the generated code and the default static rt_main.c.

  • The code generator removes the data structure for the root inports of the model unless a subsystem implemented by a nonreusable function uses the value of one or more of the inports.

  • The code generator removes the data structure for the root outports of the model except when you enable MAT-file logging or if the sample time of one or more of the outports is not the fundamental base rate (including a constant rate).

  • If you copy a subsystem block to create a block in a new model or the same model, the function interface information from the original subsystem block is not copied to the new subsystem block.

  • If you have Stateflow®, for a Stateflow chart that uses a model root inport value or that calls a subsystem that uses a model root inport value, do one of the following to generate code:

    • Clear the Execute (enter) Chart At Initialization check box in the Stateflow chart.

    • Make the Stateflow function a nonreusable function.

    • Insert a Simulink® Signal Conversion block immediately after the root inport. In the Signal Conversion block parameters dialog box, select Exclude this block from 'Block reduction' optimization.

  • If a model root inport value connects to a Simscape™ conversion block, insert a Simulink Signal Conversion block between the root inport and the Simscape conversion block. In the Signal Conversion block parameters dialog box, select Exclude this block from 'Block reduction' optimization.

  • When building a referenced model that is configured with a function interface, do not use virtual buses as inputs or outputs to the referenced model. Use nonvirtual buses instead.

  • If the C function interface is not the default, the value is ignored for the model configuration parameter Pass fixed-size scalar root inputs by value for code generation. For more information, see Pass fixed-size scalar root inputs by value for code generation.

See Also

|

Related Topics