Skip to content

Generating C source code

Code generation, i.e., turning a statechart model into source code of a programming language, is explained in the section Generating state machine code. Therefore we won’t go into the details here, but instead only put some emphasis on code generation specialties of Deep C/C++ Integration.

Creating a generator model

In the statechart model introduced above, do the following:

  1. In the project view, right-click on the project’s name. The context menu opens.
  2. In the context menu, select New → Code generator model. The itemis CREATE generator model wizard opens.
  3. Enter a filename into the File name field, e.g., c.sgen, and click Next >.
  4. In the Generator drop-down menu, select itemis CREATE Statechart C Code Generator.
  5. Select the statechart models to generate C source code for. Click Finish.

itemis CREATE creates the following generator model in the file c.sgen:

GeneratorModel for create::c {

    statechart statechart {

        feature Outlet {
            targetProject = "Geometry"
            targetFolder = "src-gen"
            libraryTargetFolder = "src"
        }
    }
}

itemis CREATE creates the target folders src and src-gen and generates the C source representing the statemachine into them.

The generated C code

Particularly interesting are the files Statechart.h and Statechart.c.

Statechart.h first includes the sc_types.h header followed by very same C header files that have been included in the statechart:

#include "sc_types.h"
#include "rectangle.h"

The generated code in Statechart.h then uses the native standard and user-defined C data types. For example, the statechart implementation defines the type StatechartIface as follows:

/*! Type definition of the data structure for the StatechartIface interface scope. */
typedef struct
{
    Rectangle a;
    Rectangle b;
    int32_t area_a;
    int32_t area_b;
    Point p;
} StatechartIface;

By including Statechart.h all definitions are available in Statechart.c, too. For example, a getter and a setter function for the Rectangle variable a are defined as follows:

Rectangle statechartIface_get_a(const Statechart* handle)
{
    return handle->iface.a;
}
void statechartIface_set_a(Statechart* handle, Rectangle value)
{
    handle->iface.a = value;
}

The external area function is called in the entry actions section of state Check:

/* Entry action for state 'Check'. */
static void statechart_enact_main_region_Check(Statechart* handle)
{
    /* Entry action for state 'Check'. */
    handle->iface.area_a = area(handle->iface.a);
    handle->iface.area_b = area(handle->iface.b);
}