codegen
Generate C/C++ code from MATLAB code
Syntax
Description
codegen
generates C or C++ code from a MATLAB® function with inputs of type options
function
-args {func_inputs
}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
{
option.func_inputs
}
codegen
generates C/C++ code from a MATLAB function that uses custom source code specified in external
options
files
function
-args {func_inputs
}files
. For more information, see Call Custom C/C++ Code from the Generated Code and Configure Build for External C/C++ Code.
codegen
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
options
files
function
-args {func_inputs
} -nargout number_args
-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
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 options
files
function1 -args {func1_inputs} ... functionN -args {funcN_inputs}-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.
codegen
generates multisignature MEX function from a MATLAB function. Provide multiple options
files
function
-args {func_inputs1} ... -args {func_inputsN}-args
specifications for input
arguments of the same entry-point function. Use the options
argument
to specify settings such as the code generation configuration object and parameters. You
must specify the build type as MEX function. Other build types (lib
,
dll
, and exe
) are not supported. For more
information, see Generate One MEX Function for Multiple Signatures.
codegen
generates code from a
MATLAB
Coder™ project file, for example, project
test.prj
.
Examples
Generate a MEX Function from a MATLAB Function
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, size, and complexity) 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 a1
-by-4
array of realdouble
values and the second input is a real scalardouble
.The actual values of these example inputs are not relevant for code generation. Any other pair of values with the same properties (class, size, and complexity) 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, size, and complexity 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.
Generate a MEX Function from a MATLAB Function That Has Multiple Signatures
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
myAdd_mex
for the
multiple signatures specified in the codegen
command. For more
information, see Generate One MEX Function for Multiple Signatures.Generate C Static Library Files in a Custom Folder
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}
Generate an Executable
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.
Generate Code That Uses a Variable-Size Input
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}
Generate Code That Uses Global Data
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}
Generate Code That Accepts an Enumerated Type Input
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}
Generate a Static Library That Accepts a Fixed-Point Input
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
.Generate a Static C++ Library That Accepts Half-Precision Inputs
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
, where
work
\codegen\lib\foo
is the current working
folder.work
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.
Convert Floating-Point MATLAB Code to Fixed-Point C Code
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
Convert codegen
command to equivalent MATLAB Coder project
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
folder,
where work
\codegen\lib\myadd
is your current working
directory.work
Input Arguments
options
— Code generation options
option value | space delimited list of option values
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 |
-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 | Specify the configuration object that contains the code generation
parameters.
For more information, see Configure Build Settings. |
-d | Store generated files in the absolute or relative path specified by
If the folder specified by
If you do not specify
the folder location, codegen/target/fcn_name.
The function does not support the following characters in folder names: asterisk (*), question-mark (?), dollar ($), and pound (#). Note Each time |
-double2single
| Generates single-precision MATLAB code using the settings that the
When used with the
.
For more information, see Generate Single-Precision MATLAB Code. You must have Fixed-Point Designer to use this option. |
-float2fixed
| When used with the
When used without the
You
must set the fixptcfg.TestBenchName = 'myadd_test'; 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
| Specify names and initial values for global variables in MATLAB files.
{g1, init1, g2, init2, ..., gn, initn}
-globals {'g', 5} Alternatively, use this format: -globals {global_var, {type, initial_value}}
Before generating code with
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
-globals {'g', coder.Constant(v)} g is a global variable with constant value
v .For more information, see Generate Code for Global Data. |
-I | Add If the path contains characters that are not 7-bit ASCII, such
as Japanese characters, it is possible that If your
'C:\Project "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, |
-o | Generate the MEX function, C/C++ library, or C/C++ executable file
with the base name
For MEX functions,
If you do not specify an output file
name for libraries and executables, the base name is
|
-O
| Optimize generated code, based on the value of
Specify If not specified,
|
-package
| Package generated standalone code and its dependencies into a
compressed ZIP file with name This packaging functionality is
also provided by the |
-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,
If you have Embedded Coder, this option also enables production of the Code Replacements report. |
-reportinfo | Export information about code generation to the variable
|
-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 | Run This
option is supported only when generating MEX functions or when using a
configuration object with |
-toproject
| Convert the You can also use the
codegen -config cfg -toproject myProjectTemplate.prj 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 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 |
function
— Name of MATLAB function to generate code from
function name
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, 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
func_inputs
— Example values for MATLAB function inputs
expression | variable | literal value | coder.Type
object
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")}
files
— Names of custom source files
file name | space delimited list of file names
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_args
— Number of output arguments in the generated entry-point function
integer
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
— Project file name
file name
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/
. MEX functions and executables are copied to the current working folder.target
/function
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 thecodegen
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
See Also
coder
| coder.typeof
| fimath
(Fixed-Point Designer) | numerictype
(Fixed-Point Designer) | mex
| fi
(Fixed-Point Designer) | coder.EnumType
| coder.runTest
| parfor
| coder.FixptConfig
| coder.config
| packNGo
Comando de MATLAB
Ha hecho clic en un enlace que corresponde a este comando de MATLAB:
Ejecute el comando introduciéndolo en la ventana de comandos de MATLAB. Los navegadores web no admiten comandos de MATLAB.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)