Main Content

codegen

Generate C or C++ code from MATLAB code

Description

codegen fun generates a C MEX function for the MATLAB® function fun with default code generation settings. Use this syntax if fun takes no input arguments or if you define the input arguments in the body of the MATLAB function by using an arguments block or assert statements.

example

codegen options fun generates C or C++ code for the MATLAB function fun with code generation settings that you specify by using the options argument. For example, use the options argument to specify the language of the generated code (C or C++) or the output type (static library, dynamic library, executable, or MEX function). Use this syntax if fun takes no input arguments or if you define the input arguments in the body of the MATLAB function by using an arguments block or assert statements.

example

codegen options fun -args inputs generates C/C++ code for the MATLAB function fun with code generation settings specified in the options argument. Use the inputs argument to specify input types.

example

codegen options fun -args inputs -nargout numOut generates C/C++ code for the MATLAB function fun using the specified code generation settings, input arguments, and number of output arguments, numOut. Use this syntax when you do not want to generate code for all of the MATLAB function outputs. You must specify -nargout numOut if fun uses varargout.

example

codegen options advSyntax generates C/C++ code for multiple entry-point functions with multiple signatures and supporting files. You can also use this syntax to generate code for a MATLAB Coder™ project.

example

Examples

collapse all

Examine the MATLAB function helloWorld. This function takes no input arguments and outputs a random integer between 1 and 100. The %#codegen directive after the function declaration prompts the MATLAB Code Analyzer to identify warnings and errors specific to code generation.

function out = helloWorld %#codegen
out = randi(100);
end

Generate a C MEX function for the helloWorld MATLAB function. The codegen command produces a C MEX function by default.

codegen helloWorld
Code generation successful.

Run the generated MEX function at the command line. The function produces a random number between 1 and 100.

helloWorld_mex
ans =

    91

Examine the MATLAB function myaddarg, which returns the sum of two values. The %#codegen directive after the function declaration prompts the MATLAB Code Analyzer to identify warnings and errors specific to code generation. This function uses 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 = myaddarg(u,v) %#codegen
arguments
    u (1,4) double
    v (1,1) double
end
y = u + v;
end

Generate a standalone C++ static library for the myaddarg function. Use the -config:lib option to specify a static library, and use the lang:c++ option to specify C++. The code generator produces C++ source code, library, object, and header files in the folder codegen/lib/myaddarg.

codegen -config:lib -lang:c++ myaddarg
Code generation successful.

Examine the MATLAB function myadd, which returns the sum of two values. The %#codegen directive after the function declaration prompts the MATLAB Code Analyzer to identify warnings and errors specific to code generation.

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

At the MATLAB command line, call the codgen command. Use the -config:lib option to generate a static library. The code generator produces C code by default. Use -args to specify that the myadd function takes two input arguments that are both scalar doubles. To learn more about specifying input arguments at the command line, see Specify Input Types at the Command Line.

codegen -config:lib myadd -args {0,0}
Code generation successful.

Examine the definition of myadd in the generated C file. The code generator produces this file in the folder codegen/lib/myadd.

/* Function Definitions */
/*
 * Arguments    : double u
 *                double v
 * Return Type  : double
 */
double myadd(double u, double v)
{
  return u + v;
}

Examine the function myops. This function performs four different operations and can have from one to four outputs. The %#codegen directive after the function declaration prompts the MATLAB Code Analyzer to identify warnings and errors specific to code generation.

function varargout = myops(a,b) %#codegen
varargout{1} = a+b;
varargout{2} = a*b;
varargout{3} = a/b;
varargout{4} = a-b;
end

Generate a C MEX function for the myops MATLAB function. The codegen command produces a C MEX function by default. Specify the input arguments by using -args:

  • To specify that a is a variable-length row vector with a maximum length of 10, use coder.typeof.

  • To specify that b is a scalar double, use 0 as an example value.

To learn more about specifying input arguments at the command line, see Specify Input Types at the Command Line.

Because myops uses varargout, you must include the -nargout argument. Use -nargout 3 to instruct the code generator to generate code for the first three output variables. To learn more about controlling the number of input or output arguments in the generated code, see Specify Number of Input or Output Arguments to Entry-Point Functions.

codegen myops -args {coder.typeof(0,[1 10],[false true]),0} -nargout 3
Code generation successful.

Run the generated MEX function at the command line with three outputs. The generated MEX function correctly produces the outputs.

[x,y,z] = myops_mex(3,4)
x =

     7


y =

    12


z =

    0.7500

Run the generated MEX function at the command line with four outputs. The generated MEX function produces an error.

[x,y,z,a] = myops_mex(3,4)
Too many output arguments for entry-point 'myops'.

Examine the MATLAB function myAdd, which returns the sum of two values.

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

At the MATLAB command line, call the codgen command. Use the -config:lib option to generate a static library and the -lang:c++ option to generate C++ code. Specify three sets of inputs for myadd by using:

  • -args {0,0} to specify two scalar doubles

  • -args {int8(0),int8(0)} to specify two 8-bit signed integers

  • -args {0,coder.typeof(0,[10,10]) to specify one scalar double and one variable-size array with a maximum size of 10-by-10

To learn more about specifying input arguments at the command line, see Specify Input Types at the Command Line.

codegen -lang:c++ -config:lib myadd -args {0,0} -args {int8(0),int8(0)} -args {0,coder.typeof(0,[10,10])}
Code generation successful.

Examine the generated header file myadd.h in the folder codegen/lib/myadd. The code generator declares three versions of the myadd function with three different sets of inputs.

// Function Declarations
real_T myadd1(real_T u, real_T v);

int8_T myadd2(int8_T u, int8_T v);

void myadd3(real_T u, const real_T v[100], real_T y[100]);
For more information, see Generate Code for Functions with Multiple Signatures.

Examine the MATLAB function myrand, which generates a random scalar value.

function r = myrand() %#codegen
r = rand();
end

Examine the file main.c, which contains the C main function. The C main function calls the C function generated from the myrand MATLAB function.

/* main.c */
#include <stdio.h>
#include <stdlib.h>
#include "myrand.h"
#include "myrand_initialize.h"
#include "myrand_terminate.h"
int main()
{
    myrand_initialize();
    printf("myrand value %g\n", myrand());
    myrand_terminate();
    return 0;
}

At the MATLAB command line, call the codgen command. Use the -config:exe option to generate an executable. The code generator produces C code by default. Instruct the code generator to include the custom source code file main.c. The code generator creates the C executable in the working folder.

codegen -config:exe myrand main.c

Test the generated executable by using the system and ispc functions. The executable produces the expected output.

if ispc
    system("myrand.exe")
else
    system("./myrand")
end
myrand value 0.814724 

ans =

     0

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

Input Arguments

collapse all

Code generation options, specified as an option value or a space-delimited list of option values. You can enter option values in any order. If options conflict, the rightmost option prevails.

Specify Code Configuration Object

To specify a code configuration object, use the -config option. You can use this object by itself or in conjunction with other option values. See Configure Code Generation and Build Settings. The code generator gives precedence to the options that you specify with the codegen function over the options that you specify by using a code configuration object.

Option ValueDescription
-config configObject

Specify the configuration object that contains the code generation settings. To create a code configuration object, use the coder.config function. For example, to create a code configuration object for a static library, use this command:

cfg = coder.config("lib");
Then, pass the created object to the codegen. For example:
codegen -config cfg foo

Control Generated Code Language

This table shows the options that control the language of the generated code. By default, the code generator produces C code compatible with the C99 (ISO) language standard. If you generate C++ code, the code generator produces C++ code compatible with the C++11 (ISO) language standard by default.

If you generate C code, C++ language standards are not supported. If you generate C++ code but specify a C language standard, the code generator uses the C math libraries available in the selected C standard and C++03 language features. For details about the supported language standards, see Change Language Standard Used for Code Generation.

Option ValueDescription
-lang:c

Generate C code.

-lang:c++

Generate C++ code.

-std:c89/c90

Generate code compatible with the C89/90 (ANSI) language standard.

-std:c99

Generate code compatible with the C99 (ISO) language standard. This language standard is the default when you generate C code.

-std:c++03

Generate code compatible with the C++03 (ISO) language standard.

-std:c++11

Generate code compatible with the C++11 (ISO) language standard. This language standard is the default when you generate C++ code.

-std:c++14

Generate code compatible with the C++14 (ISO) language standard.

-std:c++17

Generate code compatible with the C++17 (ISO) language standard.

-std:c++20

Generate code compatible with the C++20 (ISO) language standard.

Control Output Type

This table shows the options that control the type of code produced by the code generator. By default, the code generator produces a MEX function and builds the generated code.

Option ValueDescription
-config:dll

Generate a dynamic C/C++ library.

-config:exe

Generate a C/C++ executable.

-config:lib

Generate a static C/C++ library.

-config:mex

Generate a MEX function.

-c

Generate source code only. The code generator does not invoke the make command or build object code. For example, to produce a static C library for function foo and generate source code without building the generated code, use this command:

codegen -config:lib -c foo

-jit

Use just-in-time (JIT) compilation to generate a JIT MEX function, which contains an abstract representation of the MATLAB code. JIT compilation can speed up MEX function generation. You can only use this option when you generate a MEX function. This option is not compatible with some code generation options, such as including custom code or using the OpenMP library.

See Speed Up MEX Generation by Using JIT Compilation.

Specify Global Variables

Use the -globals option to specify global variables at the command line. You can also define and initialize global variables in the MATLAB workspace. See Generate Code for Global Variables.

Option ValueDescription
-globals globalArray

Define and initialize the global variables used in the MATLAB functions for which you generate code.

globalArray is a cell array of global variable names and initial values. This cell array has the format {global1,value1,global2,value2,...}. For example:

codegen foo -globals {"A",ones(4),"B",[1 2 3]} -args {0}

Alternatively, specify the global variable types by using the coder.typeof function. In this case, the cell array you pass to the -globals option has the format {global1,{type1,value1},global2,{type2,value2},...}. For example:

codegen foo -globals {"A",{coder.typeof(0,[4 4]),ones(4)}}

Specify Optimizations

This table shows the options that specify optimizations in the generated code. For additional strategies that you can use to optimize the generated code, see Optimize Generated C/C++ and MEX Code.

Option ValueDescription

-O enable:inline

-O disable:inline

Enable or disable function inlining in the generated code. By default, the code generator uses inlining. To learn more about function inlining, see Control Inlining to Fine-Tune Performance and Readability of Generated Code.

Always inlining function calls causes the code generation optimizations to process more code, and therefore, might increase code generation time.

-O enable:openmp

-O disable:openmp

Enable or disable the use of the OpenMP library in the generated code. If you enable this optimization and the OpenMP library is available, the code generator generates parfor-loops that can run on multiple threads. By default, the code generator uses the OpenMP library, if it is available.

If use disable the OpenMP optimization or the OpenMP library is not available, the code generator treats parfor-loops like for-loops and generates code that runs on a single thread.

See Control Compilation of parfor-Loops.

-rowmajor

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

Specify Debugging Options

This table shows the options that you can use to debug the generated code and the code generation process. Before generating standalone code or an accelerated MEX function, it is a best practice to check from compliance issues in your MATLAB code by generating and running a MEX function. See Check for Issues in MATLAB Code Using MEX Functions.

Option ValueDescription
-g

Enable the debug mode for the C/C++ compiler. If you enable debug mode, the code generator disables some of the optimizations that the compiler uses, which can make code generation faster. However, the generated code may execute more slowly.

-profile

Profile the generated MEX function by using the MATLAB Profiler. 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 the base MATLAB workspace. See Access Code Generation Report Information Programmatically.

-silentEnable this optimization to suppress messages when code generation succeeds without warning. This option does not suppress warning and error messages.
-test testFile

Run testFile and replace calls to the original MATLAB function with calls to the MEX function. Using this option is the same as running coder.runTest.

This option is supported only when generating MEX functions.

If you have an Embedded Coder license, you can also use this option when you generate code for software-in-the-loop (SIL) or processor-in-the-loop (PIL) verification. See Code Verification Through Software-in-the-Loop and Processor-in-the-Loop Execution (Embedded Coder).

-v

Show the code generation status and target build log messages.

Control Name and Location of Generated Files

This table shows the options that you can use to change the default base name and location of the files produced by the code generator.

Option ValueDescription
-d folder

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

  • Spaces, which can result in code generation failures in certain operating system configurations

  • Characters that are not 7-bit ASCII characters, such as Japanese characters

  • The asterisk (*), question mark (?), dollar sign ($), or number sign (#) symbols

If the folder specified by folder does not exist, the code generator creates it.

-o basename

Generate MEX, library, and executable files with the base name basename. The base name must not contain spaces, which can result in code generation failures in certain operating system configurations. If you generate a MEX function, basename must be a valid MATLAB function name.

Modify Code Generation Path

Use the -I option to instruct the code generator to search additional folders for your MATLAB function or custom code files.

Option ValueDescription
-I path

Adds path to the beginning of the code generation path. When the code generator searches for MATLAB functions or custom C/C++ files, it searches the code generation path first. Because 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, the code generator may not find the files on this path.

To include multiple paths, use -I before each path you want to include. Pass paths as character vectors or strings. For example:

codegen -I "C:\Project" -I "C:\Custom Files" foo

Export Generated Code

This table shows the options that you can use to transfer the generated code or the code generation settings to another development environment or to the MATLAB Coder app.

Option ValueDescription
-package zipFile

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

Using this option is the same as using the packNGo function.

-toproject projectFile

Save the names of the entry-point functions, -args and -nargout specifications, codegen options, and any advanced syntaxes to a MATLAB Coder project file named projectFile. Use this command if you want to transfer the codegen specifications to the MATLAB Coder app. You can also generate code using this project file by using this command:

codegen projectFile

See Convert codegen Command to Equivalent MATLAB Coder Project.

Perform Numeric Conversion

This table shows the options that you can use to perform numeric conversion of MATLAB code. You must have a Fixed-Point Designer™ license to use these options. These options are not supported entry-point functions in namespaces.

Option ValueDescription
-config:single

Generate single-precision MATLAB code.

-double2single singleConfig

Generate single-precision MATLAB code using the settings that you specify in singleConfig, which must be a coder.SingleConfig object.

The code generator produces files in the folder codegen/fun/single, where fun is the name of the entry-point function.

If you specify this option and instruct the code generator to generate standalone code, the code generator also generates single-precision C/C++ code in the folder codgen/outputType/subfolder, where:

  • outputType is:

    • mex for MEX functions

    • lib for C/C++ libraries

    • dll for C/C++ dynamic libraries

    • exe for C/C++ executables

  • subfolder is the name of the MATLAB function followed by a suffix. Specify this suffix by using the OutputFileNameSuffix property of the singleConfig object.

For more information, see Generate Single-Precision MATLAB Code.

-float2fixed float2fixedConfig

Generate fixed-point code using the settings that you specify in float2fixedConfig, which must be a coder.FixPtConfig object.

If you specify this option and instruct the code generator to generate standalone code, the code generator produces fixed-point C/C++ code. The code generator produces files in the folder codegen/outputType/fun_fixpt, where fun is the name of the entry-point function and outputType is:

  • mex for MEX functions

  • exe for embeddable C/C++ executables

  • lib for embeddable C/C++ libraries

  • dll for C/C++ dynamic libraries

If you specify this option and do not generate standalone code, the code generator produces fixed-point MATLAB code in the folder codegen/fun/fixpt.

To use this option, you must specify a test file by using the TestBenchName property of the float2fixedConfig object.

For more information, see Convert MATLAB Code to Fixed-Point C Code.

-singleC

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

Generate CUDA Code

This table shows the options that you can use when you generate CUDA® code from MATLAB code. You must have a GPU Coder™ license to use these options.

Option ValueDescription
-config gpuconfig

Specify the configuration object that contains the CUDA code generation settings. To generate this configuration object, use the function coder.gpuConfig (GPU Coder).

See Generate Code Using the Command Line Interface (GPU Coder).

-gpuprofile

Profile the generated code by using the GPU performance analyzer.

To generate and profile CUDA code using a single command, run codegen with both the -gpuprofile and -test options.

To profile non-MEX targets, you must have an Embedded Coder license.

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

MATLAB function for which to generate code, specified as a function name. The function must exist in the current working folder or be on the path. To specify a function in a MATLAB namespace, add the namespace name to the beginning of the function name, followed by a dot. The namespace must also exist in the current working folder or be on the path. If the MATLAB file is on a path that contains characters that are not 7-bit ASCII, such as Japanese characters, then the code generator may not find the file.

Example: codegen myFunction

Example: codegen myNamespace.myFunction

Input arguments to the MATLAB function fun, specified as a cell array of example values or coder.Type objects. The position of each element in the cell array must correspond to the position of the input argument in the function definition.

To create a coder.Type object, use coder.typeof or coder.newtype. To indicate that a function takes no arguments, specify inputs as an empty cell array {}.

You do not need to specify the inputs argument if you define the input arguments in the function body by using arguments blocks or assert statements. For more information, see Use Function Argument Validation to Specify Entry-Point Input Types and Specify Input Types Using assert Statements in MATLAB Code.

Example: codegen foo -args {0}

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

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

Number of output arguments to generate for the MATLAB function fun, specified as an integer. The code generator produces the specified number of output arguments in the order in which they occur in the MATLAB function definition. If the function fun uses varargout, you must specify the number of output arguments. See Specify Number of Input or Output Arguments to Entry-Point Functions.

Example: codegen foo -nargout 2

Example: codegen foo -args {0} -nargout 2

Advanced code generation syntaxes, specified a syntax fragment or a space-delimited list of syntax fragments. This table shows the syntax fragments that you can combine in any order.

Syntax FragmentDescription
fun1 -args inputs1 ... funN inputsNGenerate code for multiple entry-point functions.
fun -args inputs1 ... -args inputsNGenerate multiple signatures for an entry-point function.
file1 ... fileN

Include custom source files in the generated code. You can specify these types of files:

  • C file (.c)

  • C++ file (.cpp)

  • Header file (.h)

  • Object file (.o or .obj)

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

If custom files are on a path that contains characters that are not 7-bit ASCII, such as Japanese characters, the code generator command may not find the files.

projectFile

Generate code for a MATLAB Coder project, specified as a CODERPRJ file. The code generator produces code using the entry points, input types, and code generation options saved in the project file. See Convert codegen Command to Equivalent MATLAB Coder Project.

This syntax cannot be combined with any other syntax.

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

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

  • If you do not specify a location by using the -d option, the code generator creates C/C++ source, header, and object files in the folder codgen/outputType/functionName, where functionName is the name of the first function you pass to the codegen command and outputType is one of:

    • mex for MEX function

    • lib for C/C++ static library

    • dll for C/C++ dynamic library

    • exe for C/C++ executable

    The code generator saves generated MEX functions in the working folder.

    For example, consider this codegen command:

    codegen -config:lib fun1 fun2

    The code generator creates C source, header, and object files in the folder codgen/lib/fun1.

  • If you generate standalone code and you do not specify an output file name by using the -o option, the code generator creates source, header, and object files that begin with the name of MATLAB function which you generate code.

  • When you generate a MEX function and you do not specify an output file name by using the -o option, the code generator appends _mex to the name of the first MATLAB function in left-to-right order. For example, the name of the MEX function generated by this codegen command begins foo_mex:

    codegen foo bar

  • The code generator appends a platform- and build-specific extension to the generated files:

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

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

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

    • Platform-dependent extensions for generated MEX functions

  • 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 perform programmatic codegen calls, use the function syntax. For example:

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

Version History

Introduced in R2011a

expand all