Main Content

Debug Generated C/C++ Code

Debug the generated code if it produces unexpected outputs or stops. These outcomes are due to programmatic errors or logical fallacies in the MATLAB® code, or the behavior of certain functions in the generated code. To debug your generated C/C++ code:

  1. Review the generated MEX function to verify that this code provides the same functionality as the original MATLAB code. It is a best practice to generate a MEX function before generating standalone code for your project.

  2. Review the generated standalone code for run-time errors by setting the following options in the code configuration object:

    cfg = coder.config('lib'); % or 'dll' or 'exe'
    cfg.RuntimeChecks = 1;
    codegen myFunction -config cfg

    See RuntimeChecks in coder.CodeConfig.

  3. Review the Extended Capabilities section in the reference pages for the functions you include in your code. The behavior of some MATLAB functions differ in the generated code causing the functions to produce different but equivalent output values. The code generator checks for differences in execution at run-time and reports them as potential differences. See Potential Differences Reporting.

  4. Review calls to external C functions through coder.ceval. Verify that the data type, input, and output layout are correct. MATLAB uses a column-major layout by default.

  5. Look for any warnings that are produced during code generation.

  6. To deploy the generated code, run the initialization function before calling the entry-point function. Call the terminate function after the entry-point function. See Use Generated Initialize and Terminate Functions.

  7. If any issues persist, try compiling the code by using the debug flag.

    For MEX functions, add -g to the codegen command.

    codegen myFunction -args {1,2} -g

    For standalone code generation, create a coder.config object and modify it as shown.

    cfg = coder.config('dll');  % or 'lib' or 'exe'
    cfg.BuildConfiguration = 'Debug';
    codegen myFunction -config cfg

    For more information, see Debug Generated Code During SIL Execution (Embedded Coder).

  8. Follow the recommended workflow to generate code while using the code generator. See Workflow for Preparing MATLAB Code for Code Generation.

See Also

Related Topics