codegen - Generate C/C++ code from
MATLAB code - MATLAB ([original](http://www.mathworks.com/access/helpdesk/help/coder/ref/codegen.html)) ([raw](?raw))
Generate C/C++ code fromMATLAB code
Syntax
Description
codegen [options](#mw%5F65d7c5e8-d444-4a9a-beb5-909507aba70c) [function](#mw%5F18c379d8-47c1-4054-9024-04e63ea8194d)
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 Code Generation and Build Settings, coder.config, and the configuration object reference pages: coder.CodeConfig, coder.MexCodeConfig, and coder.EmbeddedCodeConfig.
codegen [options](#mw%5F65d7c5e8-d444-4a9a-beb5-909507aba70c) [function](#mw%5F18c379d8-47c1-4054-9024-04e63ea8194d) -args {[func_inputs](#mw%5F8cc53e3e-b706-4281-947d-4c6d2ef4126f)}
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 Code Generation and 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](#mw%5F65d7c5e8-d444-4a9a-beb5-909507aba70c) [files](#mw%5F7938a9d8-b3b7-4a68-bfea-3bd73c0c06e0) 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.
codegen [options](#mw%5F65d7c5e8-d444-4a9a-beb5-909507aba70c) [files](#mw%5F7938a9d8-b3b7-4a68-bfea-3bd73c0c06e0) [function](#mw%5F18c379d8-47c1-4054-9024-04e63ea8194d) -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 theoptions
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](#mw%5F47ec214c-9923-4131-9d4c-d1f3668556e9)
generates code from aMATLAB Coder™ project file, for example, test.prj
.
Examples
Generate MEX Function from MATLAB Function Using Input Argument Validation to Specify Input Types
Write a MATLAB function mcadd
that returns the sum of two input arguments u
and v
. Use anarguments
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.
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 a1
-by-4
array of realdouble
values and the second input is a real scalardouble
.
At the command line, call the generated MEX function mcadd_mex
. Make sure that the type and size of the values that you pass tomcadd_mex
match the input properties that you specified in thearguments
block.
Running the MATLAB function mcadd
with these input values produces the same output. This test case verifies that mcadd
andmcadd_mex
have the same behavior.
Generate a MEX Function from a MATLAB Function Using -args
to Specify Input Types
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 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 and size) results in the same generated code. See Specify Types 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 tomcadd_mex
match the input properties that you specified in thecodegen
command.
Running the MATLAB function mcadd
with these input values produces the same output. This test case verifies that mcadd
andmcadd_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
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.
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 callscoderRand
.
/* ** 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 parameteru
and uses two global variables AR
andB
.
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 Code for a Function in a MATLAB Namespace
Write a MATLAB function myMult
that returns the product of two values. Save this function in namespace+myNamespace
.
function out = myMult(a,b) out = a*b; end
Generate code for this function at the command line. Specify the functionmyMult
in namespace +myNamespace
using dot notation.
codegen myNamespace.myMult -args {0,0}
To prevent name clashes among entry-point functions with the same name in different namespaces, the files generated by the code generator begin with the name of the namespace and the name of the entry-point function. For example, use this command to call the generated MEX function.
myNamespace_myMult_mex(4,3)
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 formcsqrtfi
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_`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.
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 testmyadd
.
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. Specifymyadd
as the entry-point function. Specify the inputs tomyadd
to be variable-size matrices of typedouble
whose dimensions are unbounded. Specifycfg
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 anothercodegen
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
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 source code only. Do not invoke the make command or build object code. For example, to produce a static C/C++ library for function foo and generate source code only, use this command:codegen -config:lib -c foo This command replicates the default build type (Source Code) for the MATLAB Coder app. |
---|---|
-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 Code Generation and 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 functionsexe for embeddable C/C++ executableslib for embeddable C/C++ librariesdll 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 (#). NoteEach 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 foldercodegen/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 foldercodegen/target/folder_name.target can be: mex for MEX functionsexe for embeddable C/C++ executableslib for embeddable C/C++ librariesdll 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. This option is not supported for entry-point functions in namespaces. 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 foldercodegen/target/fcn_name_fixpt.target can be: mex for MEX functionsexe for embeddable C/C++ executableslib for embeddable C/C++ librariesdll 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 foldercodegen/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. This option is not supported for entry-point functions in namespaces. 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 ofglobal_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, usecoder.typeof. For global cell array variables, you must use this format.Before generating code withcodegen, 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, usecoder.Constant. For example:-globals {'g', coder.Constant(v)} specifies that g is a global variable with constant valuev.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 MEX function or 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.To generate and profile CUDA code using a single command, run codegen with both the -gpuprofile and -test options.GPU profiling requires the GPU Coder™ product. To profile non-MEX targets, you also need the Embedded Coder product.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 systemsPlatform-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 forparfor-loops can run on multiple threads.disable:openmp — Disable OpenMP library. With OpenMP disabled, codegen treatsparfor-loops as for-loops and generates a MEX function or C/C++ code that runs on a single thread. SeeControl 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.This option is not supported for CUDA code generation using GPU Coder. To profile generated CUDA code, use the -gpuprofile option. |
-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.This option is not supported for entry-point functions in namespaces. You must have Fixed-Point Designer to use this option. |
-std:language_standard | Generate C/C++ code compatible with the specified language standard. C++ language standards are only supported if the target language is C++.language_standard is one of these values: c89/c90 for C89/90 (ANSI)c99 for C99 (ISO)c++03 for C++03 (ISO)c++11 for C++11 (ISO)c++14 for C++14 (ISO)c++17 for C++17 (ISO)c++20 for C++20 (ISO)For example, to generate code compatible with the C++14 (ISO) language standard, use this option:-std:c++14For details of the supported language standards, see Change Language Standard Used for Code Generation. |
-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 equivalentMATLAB Coder project file named project_file_name. You can then generate code from the project file by using anothercodegen command or the MATLAB Coder app.You can also use the-toproject option to convert an incompletecodegen 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 objectcfg, run:codegen -config cfg -toproject myProjectTemplate.prjIn 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 openmyProjectTemplate.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. |
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. To specify a function in a MATLAB namespace that exists in the current working folder or on the path, add the namespace name to the beginning of the function name, followed by a dot. If the MATLAB file is on a path that contains non 7-bit ASCII characters, such as Japanese characters, then the codegen
command might not find the file.
Example: codegen myAddFunction
Example: codegen myNamespace.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, usecoder.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 Types 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
)
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.
- When generating code for entry-point functions in namespaces, the codegen command does not support the options
-double2single
,-float2fixed
, and-singleC
.
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 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 ofcodegen
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