This example shows how to generate C/C++ libraries or executables that detect and report run-time errors such as out-of-bounds array indexing. If the generated code detects an error, it reports a message and terminates the program. You can detect and fix errors that occur only on the target hardware.
Write the function getelement
that
indexes into one structure field using the value of the other structure
field.
function y = getelement(S) y = S.A(S.u); end
Create a code configuration object for a standalone library or executable. For example, create a code configuration object for a static library. Enable the code generation report.
cfg = coder.config('lib'); cfg.GenerateReport = true;
Enable generation of run-time error detection and reporting.
cfg.RuntimeChecks = true;
Define an example input that you can use to specify the properties of the input argument.
S.A = ones(2,2); S.u = 0;
Generate code.
codegen -config cfg getelement -args {S}
To open the code generation report, click the View report link.
When the report opens, you see the generated C code. You can
see the code that checks for an error and calls a function to report
the error. For example, if the code detects an out-of-bounds array
indexing error, it calls rtDynamicBoundsError
to
report the error and terminate the program.
/* Include Files */ #include "rt_nonfinite.h" #include "getelement.h" #include "getelement_rtwutil.h" #include <stdio.h> #include <stdlib.h> /* Variable Definitions */ static rtBoundsCheckInfo emlrtBCI = { 1, 4, 2, 5, "S.A", "getelement", "C:\\coder\\runtime checks\\getelement.m", 0 }; static rtDoubleCheckInfo emlrtDCI = { 2, 5, "getelement", "C:\\coder\\runtime checks\\getelement.m", 1 }; /* Function Definitions */ /* * Arguments : const struct0_T *S * Return Type : double */ double getelement(const struct0_T *S) { double d0; int i0; d0 = S->u; if (d0 != (int)floor(d0)) { rtIntegerError(d0, &emlrtDCI); } i0 = (int)d0; if (!((i0 >= 1) && (i0 <= 4))) { rtDynamicBoundsError(i0, 1, 4, &emlrtBCI); } return S->A[i0 - 1]; }
The error reporting software uses fprintf
to
write error messages to stderr
. It uses abort
to
terminate the application. If fprintf
and abort
are
not available, you must provide them. The abort
function
abruptly terminates the program. If your system supports signals,
you can catch the abort signal (SIGABRT
) so that
you can control the program termination.