Skip to Main Content Skip to Search
Product Documentation

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 to a MEX function. Optionally, you can specify custom files to include in the build. codegen applies the options to all 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 defined for project_name.

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, copy them to a different location before starting another build.

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. If you specify an empty cell array with the -args option, codegen interprets this to mean that the function takes no inputs; a compile-time error occurs if the function does have inputs.

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, codegen might not be able to 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, or .lib)

  • Template makefile (.tmf)

If these files are on a path that contains non 7-bit ASCII characters, such as Japanese characters, codegen might not be able to 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 config_object

Specify code generation parameters based on config_object, defined as one of the following:

  • 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.HardwareImplementation — Parameters of the target hardware for embeddable C/C++ code. Use for libraries or executables. If not specified, codegen generates code compatible with the MATLAB host computer.

    hw_cfg = coder.HardwareImplementation
  • 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 should not contain:

  • Spaces, as this 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

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, copy them to a different location before starting another build.

-g

Compiles MEX functions in debug mode, with optimization turned off. Use only for mex targets. If not specified, codegen generates MEX functions in optimized mode.

-globals global_values

Specify initial values for global variables in MATLAB files. Use the values in cell array global_values to initialize global variables in the function that you compile. The cell array provides the name and initial value of each global variable. Before compiling 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 might differ.

-I include_path

Add include_path to the beginning of the code generation path. It is recommended that include_path not contain spaces, as this can lead to code generation failures in certain operating system configurations.

When converting MATLAB code to C/C++ code, codegen searches the code generation path first.

include_path should not contain spaces, as this can lead to code generation failures in certain operating system configurations. If the path contains non 7-bit ASCII characters, such as Japanese characters, codegen might not be able to find files on this path.

-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 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® and Macintosh® systems

  • Platform-dependent extension for generated MEX functions

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

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, which allows you to 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:blas — Use BLAS library, if available

  • disable:blas — Do not use BLAS library

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

If not specified, codegen uses inlining and BLAS library functions 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 you specify the -launchreport 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"
    
    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 on 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 using the -globals option. Specify that input u is a real, scalar, double, 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 and 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(Enumeration) 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(Enumeration) 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}

Alternatives

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

See Also

coder | coder.EnumType | coder.runTest | coder.typeof | fi | fimath | mex | numerictype

Tutorials

How To

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2012- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS