Main Content

codegen

Generate C/C++ code from MATLAB code

Description

example

codegen options function generates C or C++ code from a MATLAB® function and builds the generated code. This syntax is applicable if either of these conditions is true:

  • The function does not have input arguments.

  • The function contains one or more arguments blocks that specify the type and size of all the input arguments.

Use the options argument to specify settings such as the code generation configuration object. The configuration object controls build type (MEX, lib, dll, or exe) and code generation parameters. For information on creating and using a configuration object, see Configure Build Settings, coder.config, and the configuration object reference pages: coder.CodeConfig, coder.MexCodeConfig, and coder.EmbeddedCodeConfig.

example

codegen options function -args {func_inputs} generates C or C++ code from a MATLAB function with inputs of type func_inputs and builds the generated code. Use the options argument to specify settings such as the code generation configuration object. The configuration object controls build type (MEX, lib, dll, or exe) and code generation parameters. For information on creating and using a configuration object, see Configure Build Settings, coder.config, and the configuration object reference pages: coder.CodeConfig, coder.MexCodeConfig, and coder.EmbeddedCodeConfig.

If the function does not have inputs, omit the function-specific -args {func_inputs} option.

codegen options files function -args {func_inputs} generates C/C++ code from a MATLAB function that uses custom source code specified in external files. For more information, see Call Custom C/C++ Code from the Generated Code and Configure Build for External C/C++ Code.

codegen options files function -args {func_inputs} -nargout number_args generates C/C++ code and controls the number of output arguments for the C/C++ function code generated from the MATLAB function. The files and options arguments are optional. Use the -nargout option when not all of the MATLAB function outputs are needed. For more information, see Specify Number of Entry-Point Function Input or Output Arguments to Generate.

codegen options files function1 -args {func1_inputs} ... functionN -args {funcN_inputs} generates C/C++ code from multiple MATLAB functions. Write the input arguments separately for each function following the function name. You can also use the -nargout option for each function. The functions that you generate code from are called entry-point functions. For more information, see Generate Code for Multiple Entry-Point Functions.

example

codegen options files function -args {func_inputs1} ... -args {func_inputsN} generates code that accepts input arguments with multiple type signatures specified by -args. For the MEX target, a single MEX function is generated that accepts all the specified signatures. However, for standalone targets, a C/C++ entry-point function is generated for each signature. Use the options argument to specify settings such as the code generation configuration object and parameters. For more information, see Generate Code for Functions with Multiple Signatures.

codegen project generates code from a MATLAB Coder™ project file, for example, test.prj.

Examples

collapse all

Write a MATLAB function mcadd that returns the sum of two input arguments u and v. Use an arguments block to declare that u is a 1-by-4 row vector of real double values and v is a real scalar double.

function y = mcadd(u,v) %#codegen
% The directive %#codegen indicates that the function
% is intended for code generation
arguments
    u (1,4) double
    v (1,1) double
end
y = u + v;
end

At the MATLAB command line, run this codegen command.

codegen mcadd

The code generator produces a MEX file mcadd_mex in the current working folder.

  • If you do not specify a build target, code generation defaults to MEX code generation. By default, the code generator names the generated MEX function mcadd_mex.

  • To allow the generation of MEX or C/C++ code with specific types, you must specify the type and size of all input variables to the MATLAB entry-point functions. In this example, you use the arguments block to declare that the first input is a 1-by-4 array of real double values and the second input is a real scalar double.

At the command line, call the generated MEX function mcadd_mex. Make sure that the type and size of the values that you pass to mcadd_mex match the input properties that you specified in the arguments block.

mcadd_mex([1 1 1 1],5)
ans =

     6     6     6     6

Running the MATLAB function mcadd with these input values produces the same output. This test case verifies that mcadd and mcadd_mex have the same behavior.

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

function y = mcadd(u,v) %#codegen
% The directive %#codegen indicates that the function
% is intended for code generation
y = u + v;
end

At the MATLAB command line, run this codegen command.

codegen mcadd -args {[0 0 0 0],0}

The code generator produces a MEX file mcadd_mex in the current working folder.

  • If you do not specify a build target, code generation defaults to MEX code generation. By default, the code generator names the generated MEX function mcadd_mex.

  • To allow the generation of MEX or C/C++ code with specific types, you must specify the properties (class and size) of all input variables to the MATLAB entry-point functions. In this example, you use the -args option to provide example values for the inputs. The code generator uses these example values to determine that the first input is a 1-by-4 array of real double values and the second input is a real scalar double.

    The actual values of these example inputs are not relevant for code generation. Any other pair of values with the same properties (class and size) results in the same generated code. See Specify Properties of Entry-Point Function Inputs.

At the command line, call the generated MEX function mcadd_mex. Make sure that the class and size of the values that you pass to mcadd_mex match the input properties that you specified in the codegen command.

mcadd_mex([1 1 1 1],5)
ans =

     6     6     6     6

Running the MATLAB function mcadd with these input values produces the same output. This test case verifies that mcadd and mcadd_mex have the same behavior.

Write a MATLAB function myAdd that returns the sum of two values.

function y = myAdd(u,v) %#codegen
y = u + v;
end

At the MATLAB command line, run this codegen command.

codegen -config:mex myAdd.m -args {1,2} -args {int8(2),int8(3)} -args {1:10,1:10} -report
The code generator creates a single MEX function myAdd_mex for the multiple signatures specified in the codegen command. For more information, see Generate Code for Functions with Multiple Signatures.

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

function y = mcadd(u,v) %#codegen
y = u + v;

Generate the C library files in a custom folder mcaddlib using the -config:lib option. Specify the first input type as a 1-by-4 vector of unsigned 16-bit integers. Specify the second input as a double-precision scalar.

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

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

function r = coderRand() %#codegen
r = rand();

Write a main C function, c:\myfiles\main.c, that calls coderRand.

/*
** main.c
*/
#include <stdio.h>
#include <stdlib.h>
#include "coderRand.h"
#include "coderRand_initialize.h"
#include "coderRand_terminate.h"
int main()
{
    coderRand_initialize();
    printf("coderRand=%g\n", coderRand());
    coderRand_terminate();
    
    puts("Press enter to quit:");
    getchar();

    return 0;
}

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 coderRand

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

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.

For a more detailed example, see Use an Example C Main in an Application.

Write a MATLAB function that takes a single input.

function y = halfValue(vector) %codegen
    y = 0.5 * vector;
end

Use coder.typeof to define an input type as a row vector of doubles with a maximum size of 1-by-16, with the second dimension variable-size.

vectorType = coder.typeof(1, [1 16], [false true]);

Generate a C static library.

codegen -config:lib halfValue -args {vectorType}

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;

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];

Generate the MEX function.

codegen use_globals -args {0}

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

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

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

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

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

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

Create a coder.EnumType object from this enumeration.

t = coder.typeof(sysMode.OFF);

Generate a MEX function for displayState.

codegen  displayState -args {t}

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

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

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.

You can generate code for MATLAB code that accepts half-precision inputs. For more information, see half.

Write a MATLAB function foo that returns the sum of two values.

function y = foo(a,b)
y = a + b;
end

At the MATLAB command line, run this codegen command.

codegen -lang:c++ -config:lib foo -args {half(0),half(0)} -report
Code generation successful: View report

The code generator produces a static C++ library in work\codegen\lib\foo, where work is the current working folder.

To view the code generation report, click View report. In the report viewer, inspect the generated C++ source code in the file foo.cpp.

real16_T foo(real16_T a, real16_T b)
{
  return a + b;
}

The generated function foo accepts and returns half-precision values. The C++ half-precision type real16_T is defined in the generated header file rtwhalf.h. Inspect the definition of the + operator of the class real16_T.

The generated code in this example converts half-precision inputs to single-precision, performs the addition operation in single-precision, and converts the result back into half-precision.

This example requires Fixed-Point Designer™.

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

function y = myadd(u,v) %#codegen
    y = u + v;
end

Write a MATLAB function, myadd_test, to test myadd.

function y = myadd_test %#codegen
    y = myadd(10,20);
end

Create a coder.FixptConfig object, fixptcfg, with default settings.

fixptcfg = coder.config('fixpt');

Set the test bench name.

fixptcfg.TestBenchName = 'myadd_test';

Create a code generation configuration object to generate a standalone C static library.

cfg = coder.config('lib');

Generate the code using the -float2fixed option.

codegen -float2fixed fixptcfg -config cfg myadd

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

function y = myadd(u,v) %#codegen
y = u + v;
end

Create a coder.CodeConfig object for generating a static library. Set TargetLang to 'C++'.

cfg = coder.config('lib');
cfg.TargetLang = 'C++';

At the MATLAB command line, create and run a codegen command. Specify myadd as the entry-point function. Specify the inputs to myadd to be variable-size matrices of type double whose dimensions are unbounded. Specify cfg as the code configuration object. Include the -toproject option to convert the codegen command to an equivalent MATLAB Coder project file with name myadd_project.prj.

codegen -config cfg myadd -args {coder.typeof(1,[Inf,Inf]),coder.typeof(1,[Inf,Inf])} -toproject myadd_project.prj
Project file 'myadd_project.prj' was successfully created.
Open Project

The code generator creates the project file myadd_project.prj in the current working folder. Running codegen with the -toproject option does not generate code. It only creates the project file.

Generate code from myadd_project.prj by using another codegen command.

codegen myadd_project.prj

The code generator produces a C++ static library function myadd in the work\codegen\lib\myadd folder, where work is your current working directory.

Input Arguments

collapse all

The codegen command gives precedence to individual command-line options over options specified by a configuration object. If command-line options conflict, the rightmost option prevails. The order of the options and the other syntax elements is interchangeable.

Specified as one or more of these values:

-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 Fixed-Point Designer.

-config config_object

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

  • coder.CodeConfig — Parameters for standalone C/C++ library or executable generation if Embedded Coder® is not 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 Embedded Coder 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')

For more information, see Configure Build Settings.

-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.

-double2single 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.

For more information, see Generate Single-Precision MATLAB Code. You must have Fixed-Point Designer 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';
This command specifies that myadd_test is the test file for the floating-point to fixed-point configuration object fixptcfg.

For more information, see Convert MATLAB Code to Fixed-Point C Code. You must have Fixed-Point Designer 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.

For more information, see Generate Code for Global Data.

-gpuprofile

Enable GPU profiling of the generated code by using GPU performance analyzer.

The GPU performance analyzer runs a software-in-the-loop (SIL) execution that collects metrics on CPU and GPU activities in the generated code. The GPU performance analyzer provides a report containing a chronological timeline plot that you can use to visualize, identify, and mitigate performance bottlenecks in the generated CUDA® code.

GPU profiling requires the GPU Coder™ and Embedded Coder products.

For GPU profiling, the configuration object must be a coder.EmbeddedCodeConfig with the build type set to 'lib', 'dll', or 'exe'.

For more information, see GPU Performance Analyzer (GPU Coder).

-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. For more information, see Paths and File Infrastructure Setup.

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.

To include multiple paths, use -I before each path you want to include. Enclose paths containing spaces in single quotes. For example:

-I C:\Project -I 'C:\Custom Files'
-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.

-lang:c

Specify the language to use in the generated code as C.

If you do not specify any target language, the code generator produces C code.

-lang:c++

Specify the language to use in the generated code as C++.

-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. To learn more about function inlining, see Control Inlining to Fine-Tune Performance and Readability of Generated Code.

  • 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. See Control Compilation of parfor-Loops.

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

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

-package zip_file_name

Package generated standalone code and its dependencies into a compressed ZIP file with name zip_file_name. You can then use the ZIP file to relocate, unpack, and rebuild the code files in another development environment.

This packaging functionality is also provided by the packNGo function.

-preservearraydims

Generate code that uses N-dimensional indexing. For more information, see Generate Code That Uses N-Dimensional Indexing.

-profile

Enable profiling of generated MEX function by using the MATLAB Profiler. For more information, see Profile MEX Functions by Using MATLAB Profiler.

-report

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

If you have Embedded Coder, this option also enables production of the Code Replacements report.

-reportinfo info

Export information about code generation to the variable info in your base MATLAB workspace. See Access Code Generation Report Information Programmatically.

-rowmajor

Generate code that uses row-major array layout. Column-major layout is the default. For more information, see Generate Code That Uses Row-Major Array Layout.

-silent

If code generation succeeds without warning, suppress all messages, including when you generate a report.

Warning and error messages are displayed.

-singleC

Generate single-precision C/C++ code. For more information, see Generate Single-Precision C Code at the Command Line.

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

-std:c89/c90

Use the C89/90 (ANSI) language standard for the generated code.

-std:c99

Use the C99 (ISO) language standard for the generated code.

-std:c++03

Use the C++03 (ISO) language standard for the generated code. You can use this library only if you generate C++ code.

-std:c++11

Use the C++11 (ISO) language standard for the generated code. You can use this library only if you generate C++ code.

-test test_file

Run test_file, replacing a call to the original MATLAB function with a call to the MEX function. Using this option is the same as running coder.runTest.

This option is supported only when generating MEX functions or when using a configuration object with VerificationMode set to 'SIL' or 'PIL'. Creation of a configuration object that has the VerificationMode parameter requires the Embedded Coder product.

-toproject project_file_name

Convert the codegen command to an equivalent MATLAB Coder project file named project_file_name. You can then generate code from the project file by using another codegen command or the MATLAB Coder app.

You can also use the -toproject option to convert an incomplete codegen command to a project file. For example, to create a project file myProjectTemplate.prj that contains only the code generation parameters stored in the configuration object cfg, run:

codegen -config cfg -toproject myProjectTemplate.prj
In this case, myProjectTemplate.prj does not contain specifications of entry-point functions or input types. So, you cannot generate code from this project file. You can open myProjectTemplate.prj in the MATLAB Coder app and use it as a template to create full project files that you can use to generate code.

Running codegen with the -toproject project_file_name option does not generate code. It creates only the project file.

See Convert codegen Command to Equivalent MATLAB Coder Project.

-v

Enable verbose mode to show code generation status and target build log messages.

-?

Display help for codegen command.

Specified as a function existing in the current working folder or on the path. If the MATLAB file is on a path that contains non 7-bit ASCII characters, such as Japanese characters or inside a package name starting with +, then the codegen command might not find the file.

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

Example: codegen myAddFunction

Example values that define the size, class, and complexity of the inputs of the preceding MATLAB function. The position of the input in the cell array must correspond to the position of the input argument in the MATLAB function definition. Alternatively, instead of an example value, you can provide a coder.Type object. To create a coder.Type object, use coder.typeof.

To generate a function that has fewer input arguments than the function definition has, omit the example values for the arguments that you do not want.

For more information, see Specify Properties of Entry-Point Function Inputs.

Example: codegen foo -args {1}

Example: codegen foo2 -args {1, ones(3,5)}

Example: codegen foo3 -args {1, ones(3,5), coder.typeof("hello")}

Space-separated list of custom files to include in generated code. The order of the options, external files, and function specifications is interchangeable. You can include these 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)

    Note

    Support for template makefiles (TMF) will be removed in a future release. Instead, use the toolchain approach for building the generated code.

If these files are on a path that contains non 7-bit ASCII characters, such as Japanese characters, the codegen command might not find the files.

Example: codegen foo myLib.lib

Number of output arguments in the C/C++ entry-point function generated for the preceding MATLAB function. The code generator produces the specified number of output arguments in the order in which they occur in the MATLAB function definition.

Example: codegen myMLfnWithThreeOuts -nargout 2

Project file created from the MATLAB Coder app. The code generator uses the project file to set entry-point functions, input type definitions, and other options. To open the app and create or modify a project file, use the coder function.

Example: codegen foo.prj

Limitations

  • You cannot generate code for MATLAB scripts. Rewrite the script as a function to generate code.

  • Generating code when the current folder is a private folder or an @ folder is not supported, because these folders have special meanings in MATLAB. You can generate code that invokes methods in @ folders and functions in private folders.

Tips

  • By default, code is generated in the folder codegen/target/function. MEX functions and executables are copied to the current working folder.

  • To simplify your code generation process, you can write your code generation commands in a separate script. In the script, define your function input types and code generation options. To generate code, call the script.

  • 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 the files to a different location.

  • 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.

  • You can call codegen by using function syntax. Specify the codegen arguments as character vectors or string scalars. For example:

    codegen('myfunction','-args',{2 3},'-report')
    
  • To provide a string scalar as an input or to specify a codegen argument as a string scalar, use the function syntax. For example:

    codegen('myfunction','-args',"mystring",'-report')
    codegen("myfunction","-args","mystring","-report")
    

    Providing string scalar inputs to the command form of codegen can produce unexpected results. See Choose Command Syntax or Function Syntax.

  • To perform programmatic codegen calls, use the function syntax. For example:

    A = {'myfunction','-args',{2 3}};
    codegen(A{:})
    

Version History

Introduced in R2011a