codegen

Generate C/C++ code from MATLAB code

Syntax

codegen options files fcn_1 args... fcn_n args
codegen project_name

Description

codegen options files fcn_1 args... fcn_n args translates the MATLAB® functions fcn_1 through fcn_n to a C/C++ static or dynamic library, executable, or MEX function. Optionally, you can specify custom files to include in the build. codegen applies the options to functions fcn_1 through fcn_n. It applies args to the preceding function only (fcn_n). If you specify C++, MATLAB Coder™ wraps the C code into .cpp files so that you can use a C++ compiler and interface with external C++ applications. It does not generate C++ classes.

codegen project_name generates output for the MATLAB Coder project project_name. codegen generates a MEX function, C/C++ static or dynamic library, or C/C++ executable depending on the project settings that you defined for project_name.

By default, codegen generates files in the folder codegen/target/fcn_name.

target can be:

  • mex for MEX functions

  • exe for embeddable C/C++ executables

  • lib for embeddable C/C++ static libraries

  • dll for C/C++ dynamic libraries

fcn_name is the name of the first MATLAB function (alphabetically) at the command line.

codegen copies the MEX function and executable file to the current working folder or to the output folder that the -d option specifies.

Each time codegen generates the same type of output for the same code or project, it removes the files from the previous build. If you want to preserve files from a previous build, before starting another build, copy them to a different location

Input Arguments

args

args applies only to the preceding function, fcn_n.

-args example_inputs

Define the size, class, and complexity of all MATLAB function inputs. Use the values in example_inputs to define these properties. example_inputs must be a cell array that specifies the same number and order of inputs as the MATLAB function. codegen interprets an empty cell array with the -args option to mean that the function takes no inputs. If the function does have inputs, a compile-time error occurs.

Specify the example inputs immediately after the function to which they apply.

Use the coder.typeof function to create example inputs.

fcn_1

fcn_1... fcn_n are the MATLAB entry-point functions from which to generate a MEX function, C/C++ library, or C/C++ executable code. In most cases, you have only one function. Make sure that fcn_1... fcn_n are suitable for code generation.

If these MATLAB functions are in files on a path that contains non 7-bit ASCII characters, such as Japanese characters, it is possible that codegen does not find them.

If you are using the LCC compiler, do not name an entry-point function main.

files

Space-separated list of custom files to include in generated code. You can include the following types of files:

  • C file (.c)

  • C++ file (.cpp)

  • Header file (.h)

  • Object file (.o or .obj)

  • Library (.a, .so, .dylib, or .lib)

  • Template makefile (.tmf)

If these files are on a path that contains non 7-bit ASCII characters, such as Japanese characters, it is possible that codegen does not find them.

options

Choice of compiler options. codegen gives precedence to individual command-line options over options specified using a configuration object. If command-line options conflict, the rightmost option prevails.

-c

Generate C/C++ code, but do not invoke the make command.

-config:dll

Generate a dynamic C/C++ library using the default configuration parameters.

-config:exe

Generate a static C/C++ executable using the default configuration parameters.

-config:lib

Generate a static C/C++ library using the default configuration parameters.

-config:mex

Generate a MEX function using the default configuration parameters.

-config:single

Generate single-precision MATLAB code using the default configuration parameters.

Requires a Fixed-Point Designer™ license.

-config config_object

Specify the configuration object that contains the code generation parameters. config_object is based on one of the following classes:

  • coder.CodeConfig — Parameters for standalone C/C++ library or executable generation if no Embedded Coder® license is available.

    % Configuration object for a dynamic linked library
    cfg = coder.config('dll')
    % Configuration object for an executable
    cfg = coder.config('exe')
    % Configuration object for a static standalone library
    cfg = coder.config('lib')
    

  • coder.EmbeddedCodeConfig— Parameters for a standalone C/C++ library or executable generation if an Embedded Coder license is available.

    % Configuration object for a dynamic linked library
    ec_cfg = coder.config('dll')
    % Configuration object for an executable
    ec_cfg = coder.config('exe')
    % Configuration object for a static standalone library
    ec_cfg = coder.config('lib')
    

  • coder.MexCodeConfig — Parameters for MEX code generation.

    mex_cfg = coder.config
    % or 
    mex_cfg = coder.config('mex')

-d out_folder

Store generated files in the absolute or relative path specified by out_folder. out_folder must not contain:

  • Spaces, as spaces can lead to code generation failures in certain operating system configurations.

  • Non 7-bit ASCII characters, such as Japanese characters,

If the folder specified by out_folder does not exist, codegen creates it.

If you do not specify the folder location, codegen generates files in the default folder:

codegen/target/fcn_name. 

target can be:

  • mex for MEX functions

  • exe for embeddable C/C++ executables

  • lib for embeddable C/C++ libraries

  • dll for C/C++ dynamic libraries

fcn_name is the name of the first MATLAB function (alphabetically) at the command line.

The function does not support the following characters in folder names: asterisk (*), question-mark (?), dollar ($), and pound (#).

    Note:   Each time codegen generates the same type of output for the same code, it removes the files from the previous build. If you want to preserve files from a previous build, before starting another build, copy them to a different location.

-doubles2single double2single_cfg_name

Generates single-precision MATLAB code using the settings that the coder.singleConfig object double2single_cfg_name specifies. codegen generates files in the folder codegen/fcn_name/single.

fcn_name is the name of the entry-point function.

When used with the -config option, also generates single-precision C/C++ code. codegen generates the single-precision files in the folder codegen/target/folder_name

. target can be:

  • mex for MEX functions

  • exe for embeddable C/C++ executables

  • lib for embeddable C/C++ libraries

  • dll for C/C++ dynamic libraries

folder_name is the concatenation of fcn_name and singlesuffix.

singlesuffix is the suffix that the coder.singleConfig property OutputFileNameSuffix specifies. The single-precision files in this folder also have this suffix.

You must have a Fixed-Point Designer license to use this option.

-float2fixed float2fixed_cfg_name

When used with the -config option, generates fixed-point C/C++ code using the settings that the floating-point to fixed-point conversion configuration object float2fixed_cfg_name specifies.

codegen generates files in the folder codegen/target/fcn_name_fixpt. target can be:

  • mex for MEX functions

  • exe for embeddable C/C++ executables

  • lib for embeddable C/C++ libraries

  • dll for C/C++ dynamic libraries

fcn_name is the name of the entry-point function.

When used without the -config option, generates fixed-point MATLAB code using the settings that the floating-point to fixed-point conversion configuration object named float2fixed_cfg_name specifies. codegen generates files in the folder codegen/fcn_name/fixpt.

You must set the TestBenchName property of float2fixed_cfg_name. For example:

fixptcfg.TestBenchName = 'myadd_test';
specifies that myadd_test is the test file for the floating-point to fixed-point configuration object fixptcfg.

You must have a Fixed-Point Designer license to use this option.

-g

Specify whether to use the debug option for the C compiler. If you enable debug mode, the C compiler disables some optimizations. The compilation is faster, but the execution is slower.

-globals global_values

Specify names and initial values for global variables in MATLAB files.

global_values is a cell array of global variable names and initial values. The format of global_values is:

{g1, init1, g2, init2, ..., gn, initn}

gn is the name of a global variable specified as a character vector. initn is the initial value. For example:

-globals {'g', 5}

Alternatively, use this format:

-globals {global_var, {type, initial_value}}

type is a type object. To create the type object, use coder.typeof. For global cell array variables, you must use this format.

Before generating code with codegen, initialize global variables. If you do not provide initial values for global variables using the -globals option, codegen checks for the variable in the MATLAB global workspace. If you do not supply an initial value, codegen generates an error.

MATLAB Coder and MATLAB each have their own copies of global data. For consistency, synchronize their global data whenever the two interact. If you do not synchronize the data, their global variables can differ.

To specify a constant value for a global variable, use coder.Constant. For example:

-globals {'g', coder.Constant(v)}
specifies that g is a global variable with constant value v.

-I include_path

Add include_path to the beginning of the code generation path. When codegen searches for MATLAB functions and custom C/C++ files, it searches the code generation path first. It does not search for classes on the code generation path. Classes must be on the MATLAB search path.

Spaces in include_path can lead to code generation failures in certain operating system configurations. If the path contains characters that are not 7-bit ASCII , such as Japanese characters, it is possible that codegen does not find files on this path.

-jit

Use just-in-time (JIT) compilation for generation of a MEX function. JIT compilation can speed up MEX function generation. This option applies only to MEX function generation. This option is not compatible with certain code generation features or options, such as custom code or using the OpenMP library.

-launchreport

Generate and open a code generation report. If you do not specify this option, codegen generates a report only if error or warning messages occur or if you specify the -report option.

-o output_file_name

Generate the MEX function, C/C++ library, or C/C++ executable file with the base name output_file_name plus an extension:

  • .a or .lib for C/C++ static libraries

  • .exe or no extension for C/C++ executables

  • .dll for C/C++ dynamic libraries on Microsoft® Windows® systems

  • .so for C/C++ dynamic libraries on Linux® systems

  • .dylib for C/C++ dynamic libraries on Mac systems

  • Platform-dependent extension for generated MEX functions

output_file_name can be a file name or include an existing path. output_file_name must not contain spaces, as spaces can lead to code generation failures in certain operating system configurations.

For MEX functions, output_file_name must be a valid MATLAB function name.

If you do not specify an output file name for libraries and executables, the base name is fcn_1. fcn_1 is the name of the first MATLAB function specified at the command line. For MEX functions, the base name is fcn_1_mex. You can run the original MATLAB function and the MEX function and compare the results.

-O optimization_option

Optimize generated code, based on the value of optimization_option:

  • enable:inline — Enable function inlining

  • disable:inline — Disable function inlining

  • enable:openmp — Use OpenMP library if available. Using the OpenMP library, the MEX functions or C/C++ code that codegen generates for parfor-loops can run on multiple threads.

  • disable:openmp — Disable OpenMP library. With OpenMP disabled, codegen treats parfor-loops as for-loops and generates a MEX function or C/C++ code that runs on a single thread.

Specify-O at the command line once for each optimization.

If not specified, codegen uses inlining and OpenMP for optimization.

-report

Generate a code generation report. If you do not specify this option, codegen generates a report only if error or warning messages occur or if you specify the -launchreport option.

If you have an Embedded Coder license, this option also enables the Code Replacements and Static Code Metrics reports.

-singleC

Generate single-precision C/C++ code.

You must have a Fixed-Point Designer license to use this option.

-v

Enable verbose mode to show build steps. Use when generating libraries or executables only.

-?

Display help for codegen command.

project_name

Name of the MATLAB Coder project that you want codegen to build. The project name must not contain spaces.

Examples

Generate a MEX function from a MATLAB function that is suitable for code generation.

  1. Write a MATLAB function, coderand, that generates a random scalar value from the standard uniform distribution on the open interval (0,1).

    function r = coderand() %#codegen
    % The directive %#codegen indicates that the function
    % is intended for code generation
    r = rand();
  2. Generate and run the MEX function. By default, codegen names the generated MEX function coderand_mex.

    codegen coderand
    coderand_mex

Generate C executable files from a MATLAB function that is suitable for code generation. Specify the main C function as a configuration parameter.

  1. Write a MATLAB function, coderand, that generates a random scalar value from the standard uniform distribution on the open interval (0,1).

    function r = coderand() %#codegen
    r = rand();
  2. Write a main C function, c:\myfiles\main.c, that calls coderand.

    /*
    ** main.c
    */
    #include <stdio.h>
    #include <stdlib.h>
    #include "coderand.h"
    #include "coderand_initialize.h"
    #include "coderand_terminate.h"
    int main()
    {
        coderand_initialize();
        
        printf("coderand=%g\n", coderand());
        
        coderand_terminate();
        
        return 0;
    }
  3. Configure your code generation parameters to include the main C function, then generate the C executable.

    cfg = coder.config('exe')
    cfg.CustomSource = 'main.c'
    cfg.CustomInclude = 'c:\myfiles'
    codegen -config cfg coderand

    codegen generates a C executable, coderand.exe, in the current folder, and supporting files in the default folder, codegen/exe/coderand.

    This example shows how to specify a main function as a parameter in the configuration object coder.CodeConfig. Alternatively, you can specify the file containing main() separately at the command line. You can use a source, object, or library file.

Generate C library files in a custom folder from a MATLAB function with inputs of different classes and sizes. The first input is a 1-by-4 vector of unsigned 16-bit integers. The second input is a double-precision scalar.

  1. Write a MATLAB function, mcadd, that returns the sum of two values.

    function y = mcadd(u,v) %#codegen
    y = u + v;
  2. Generate the C library files in a custom folder mcaddlib using the -config:lib option.

    codegen -d mcaddlib -config:lib  mcadd -args {zeros(1,4,'uint16'),0} 

Generate C library files from a MATLAB function that takes a fixed-point input.

  1. Write a MATLAB language function, mcsqrtfi, that computes the square root of a fixed-point input.

    function y = mcsqrtfi(x) %#codegen
    y = sqrt(x);

  2. Define numerictype and fimath properties for the fixed-point input x and generate C library code for mcsqrtfi using the -config:lib option.

    T = numerictype('WordLength',32, ...
                    'FractionLength',23, ...
                    'Signed',true)
    F = fimath('SumMode','SpecifyPrecision', ...
               'SumWordLength',32, ...
               'SumFractionLength',23, ...
               'ProductMode','SpecifyPrecision', ...
               'ProductWordLength',32, ...
               'ProductFractionLength',23)
    % Define a fixed-point variable with these
    %  numerictype and fimath properties
    myfiprops = {fi(4.0,T,F)}
    codegen -config:lib mcsqrtfi -args myfiprops 
    codegen generates C library and supporting files in the default folder, codegen/lib/mcsqrtfi.

Specify global data at the command line.

  1. Write a MATLAB function, use_globals, that takes one input parameter u and uses two global variables AR and B.

    function y = use_globals(u)
    %#codegen
    % Turn off inlining to make 
    % generated code easier to read
    coder.inline('never');
    global AR;
    global B;
    AR(1) = u(1) + B(1);
    y = AR * 2;
  2. Generate a MEX function. By default, codegen generates a MEX function named use_globals_mex in the current folder. Specify the properties of the global variables at the command line by using the -globals option. Specify that input u is a real, scalar, double, by using the -args option.

    codegen -globals {'AR', ones(4), 'B', [1 2 3 4]} ...
    	use_globals -args {0}

Alternatively, you can initialize the global data in the MATLAB workspace. At the MATLAB prompt, enter:

global AR B;
AR = ones(4);
B = [1 2 3];
Compile the function to generate a MEX file named use_globalsx.
codegen use_globals -args {0}

Generate output for a MATLAB Coder project, test_foo.prj, that includes one file, foo.m, and has it output type set to C/C++ Static Library.

codegen test_foo.prj

codegen generates a C library, foo, in the codegen\lib\foo folder.

Generate a MEX function for a function, displayState, that has an input parameter that is an enumerated type.

  1. Write a function, displayState, that uses enumerated data to activate an LED display, based on the state of a device. It lights a green LED display to indicate the ON state. It lights a red LED display to indicate the OFF state.

    function led = displayState(state)
    %#codegen
    
    if state == sysMode.ON
        led = LEDcolor.GREEN;
    else
        led = LEDcolor.RED;
    end

  2. Define an enumeration LEDColor. On the MATLAB path, create a file named 'LEDColor' containing:

    classdef LEDcolor < int32
        enumeration
            GREEN(1),
            RED(2),
        end
    end

  3. Create a coder.EnumType object using a value from an existing MATLAB enumeration.

    1. Define an enumeration sysMode. On the MATLAB path, create a file named 'sysMode' containing:

      classdef sysMode < int32
        enumeration
          OFF(0)
          ON(1)
        end
      end

    2. Create a coder.EnumType object from this enumeration.

      t = coder.typeof(sysMode.OFF);

  4. Generate a MEX function for displayState.

    codegen  displayState -args {t}

Convert floating-point MATLAB code to fixed-point C code

This example requires a Fixed-Point Designer license.

  1. Write a MATLAB function, myadd, that returns the sum of two values.

    function y = myadd(u,v) %#codegen
        y = u + v;
    end
  2. Write a MATLAB function, myadd_test, to test myadd.

    function y = myadd_test %#codegen
        y = myadd(10,20);
    end
    
  3. Create a coder.FixptConfig object, fixptcfg, with default settings.

    fixptcfg = coder.config('fixpt');
  4. Set the test bench name.

    fixptcfg.TestBenchName = 'myadd_test';
  5. Create a code generation configuration object to generate a standalone C static library.

    cfg = coder.config('lib');

  6. Generate the code using the -float2fixed option.

    codegen -float2fixed fixptcfg -config cfg myadd

Convert double-precision MATLAB code to single-precision C code.

This example requires a Fixed-Point Designer license.

Suppose that myfunction takes two double scalar inputs. Use the -singleC option to generate single-precision C/C++ code.

codegen -singleC myfunction -args {1 2}

Related Examples

Alternatives

Use the coder function to open the MATLAB Coder app and create a MATLAB Coder project. The app provides a user interface that facilitates adding MATLAB files, defining input parameters, and specifying build parameters.

Introduced in R2011a

Was this topic helpful?