Generating Standalone C/C++ Executables from MATLAB Code
R2026bGenerate C Executable by Using the MATLAB Coder App
This example shows how to generate a C executable from MATLAB® code using the MATLAB Coder™ app. In this example, you generate an executable for a MATLAB function that generates a random scalar value.
First, you create an example MATLAB function and test file. Then, you:
Add the MATLAB function as an entry-point function by using the MATLAB Coder app.
Generate an example C
mainfunction that calls the generated library function.Modify the generated
main.candmain.h.Modify the code generation settings so that the app can find the modified
main.candmain.h.Generate the executable.
Create Example MATLAB Function and Test File
In a local writable folder, create a MATLAB function, coderand, that generates a random scalar
value from the standard uniform distribution on the open interval
(0,1):
function r = coderand() %#codegen r = rand();
In the same local writable folder, create a MATLAB file, coderand_test.m, that calls
coderand.
function y = coderand_test()
y = coderand();
Add Entry-Point Function
Open the MATLAB Coder app from the Apps tab on the MATLAB Toolstrip.
In the Create MATLAB Coder Project dialog box, specify a name for your project.
For this example, enter coderand.coderprj. The app creates the
project file in the working folder.
Open the Entry Points pane by clicking the Entry
Points button on the MATLAB
Coder tab of the toolstrip. Enter coderand as the name of
the entry-point function. Because the coderand function has
no input arguments, you do not need to specify
input types.
Before generating standalone code, it is a best practice to generate a MEX
function from your MATLAB code, and run the generated MEX function using a test file. This step
can help to identify issues during code generation and at run time that can be harder
to diagnose in standalone code. To perform this step, MATLAB
Coder tab of the toolstrip, click Run Generated MEX > Run
file. Select the test file coderand_test.m. The app
successfully generates and runs the MEX
file.
Generate C main Function
When you generate an executable, you must provide a C/C++ main function. By
default, when you generate C/C++ static libraries, dynamically linked libraries, or
executables, the code generator produces a main function. This
generated main function is a template that you modify for your application. See Incorporate Generated Code Using an Example Main Function. After you copy
and modify the generated main function, you can use it for generation of the C/C++
executable. Alternatively, you can write your own main function.
Before you generate the executable for coderand, generate a
main function that calls coderand.
By default, the MATLAB Coder app generates C static libraries. To verify these settings, on the MATLAB Coder tab of the toolstrip, click the Language button to verify that the language of the generated code is C, and click the Output Type button to verify that the output type is a static library.
Click Settings to open the Code Generation Settings dialog box. On the Advanced pane, verify that the Generate example main parameter is set to
Generate, but do not compile, an example main function.On the MATLAB Coder tab of the toolstrip, click Generate Code. The app generates the files
main.candmain.hin the foldercodegen/lib/coderand/examples.
Modify Generated Example main Files
Because subsequent code generation can overwrite the generated example files, copy
the generated main files to a writable folder before you modify
them. For this example, copy main.c and main.h
to the working directory.
Open
main.c.Modify the
main_coderandfunction so that it prints the results of thecoderandcall. Delete this C code:void main_coderand(void) { double r; /* Call the entry-point 'coderand'. */ r = coderand(); }Replace the deleted C code with this code:
void main_coderand(void) { /* Call the entry-point 'coderand' and print the results. */ printf("coderand=%g\n", coderand()); }For this example, the
mainfunction does not have arguments. In themainfunction, delete these lines:(void)argc; (void)argv;Change the definition of the
mainfunction. Delete this line:int main(int argc, char **argv)Replace the deleted line with this line:
int main()Save your changes.
Open
main.hUnder the
/* Include Files */comment, add this line:#include <stdio.h>Change the declaration of the
mainfunction. Delete this line:extern int main(int argc, char **argv);Replace the deleted line with this line:
extern int main();Save your changes.
Modify Code Generation Settings
After modifying the generated example main files, you must modify the code generation settings to instruct the code generator to create an executable C function using the modified C files.
To change the output type to executable, on the MATLAB Coder tab of the toolstrip, click Output Type > Executable (.exe).
To instruct the code generator to use the modified C main function, open the Code Generation Settings dialog box by clicking Settings on the MATLAB Coder tab of the toolstrip. Enter
main.cin the Additional source files box on the Custom Code pane.
Generate Executable
To generate the executable file, click Generate Code and
Build on the MATLAB
Coder tab of the toolstrip. The app generates the file
coderand.exe in the working folder.
To run the executable in MATLAB on a Windows® platform, enter this command in the Command Window:
system('coderand')The coderand function executable in this example returns a
fixed value between 0 and 1. To generate code that produces a new value at each
execution, use the RandStream function in your MATLAB code.
Generate a C Executable at the Command Line
In this example, you create a MATLAB function that generates a random scalar value and a main C function that calls this MATLAB function. You then specify types for the function input parameters, specify the main function, and generate a C executable for the MATLAB code.
Write a MATLAB function,
coderand, that generates a random scalar value from the standard uniform distribution on the open interval (0,1):function r = coderand() %#codegen r = rand();
Write a main C function,
c:\myfiles\main.c, that callscoderand. For example:/* ** main.c */ #include <stdio.h> #include <stdlib.h> #include "coderand.h" #include "coderand_terminate.h" int main() { /* The initialize function is called automatically from the generated entry-point function. So, a call to initialize is not included here. */ printf("coderand=%g\n", coderand()); coderand_terminate(); return 0; }Note
In this example, because the default file partitioning method is to generate one file for each MATLAB file, you include
"coderand_terminate.h". If your file partitioning method is set to generate one file for all functions, do not include"coderand_terminate.h".Configure your code generation parameters to include the main C function and then generate the C executable:
cfg = coder.config('exe'); cfg.CustomSource = 'main.c'; cfg.CustomInclude = 'c:\myfiles'; codegen -config cfg coderand
codegengenerates a C executable,coderand.exe, in the current folder. It generates supporting files in the default folder,codegen/exe/coderand.codegengenerates the minimal set of#includestatements for header files required by the selected code replacement library.
Generate a C Executable with String Input Arguments
This example generates a C executable from a MATLAB function that accepts a character vector input argument. The generated
executable receives the text as a command-line argument. To pass text from the command
line to a generated executable, define the input as a character vector rather than a
string scalar. The code generator maps character vectors to
emxArray_char_T arrays in the generated code. You can populate
these arrays directly from a C string by using the generated
emxCreateWrapper helper function. String scalars map to an
rtString structure. This structure wraps the character data in an
additional layer, which complicates command-line argument passing.
When you generate an executable for a function that has input arguments, you must
write a main function that passes the command-line arguments to the
generated entry-point function.
For variable-size character array inputs, the generated code represents the input as
an emxArray type. Use the generated
emxCreateWrapper helper function to wrap the command-line argument
before passing it to the entry-point function.
Write a MATLAB function,
writeGreeting, that takes a character vector input and writes a greeting to a text file:function writeGreeting(name) %#codegen fid = fopen('greeting.txt','w'); fprintf(fid,'Hello, %s!\n',name); fclose(fid); end
Define the input type as a variable-size character vector and generate a static library to produce an example
mainfunction:cfg = coder.config("lib"); codegen -config cfg writeGreeting -args {coder.typeof('a',[1,Inf])}
The code generator produces example
main.candmain.hfiles in the foldercodegen/lib/writeGreeting/examples.Copy the generated
main.candmain.hto your working folder. Openmain.cand modify it to pass the command-line argument to the entry-point function.In the
/* Function Declarations */section, add a forward declaration for themain_writeGreetingfunction:static void main_writeGreeting(const char* str);Modify the
main_writeGreetingfunction to accept aconst char*argument. UseemxCreateWrapper_char_Tto create the expected data structure:static void main_writeGreeting(const char* str) { emxArray_char_T *name; /* Wrap the C string in an emxArray */ name = emxCreateWrapper_char_T((char*)str, 1, (int)strlen(str)); /* Call the entry-point function */ writeGreeting(name); /* Free the emxArray to avoid memory leaks */ emxDestroyArray_char_T(name); }In the
mainfunction, passargv[1]to the modifiedmain_writeGreetingfunction:int main(int argc, char **argv) { if (argc < 2) { printf("Usage: writeGreeting <name>\n"); return 1; } writeGreeting_initialize(); main_writeGreeting(argv[1]); writeGreeting_terminate(); return 0; }Open
main.h. Under the/* Include Files */comment, add:#include <stdio.h> #include <string.h>In the
/* Function Declarations */section, remove the declaration formain_writeGreeting. Because the function is declaredstaticinmain.c, it does not need anexterndeclaration in the header file.Configure your code generation parameters to include the modified main function and generate the executable:
cfg = coder.config("exe"); cfg.CustomSource = "main.c"; cfg.CustomInclude = "."; codegen -config cfg writeGreeting -args {coder.typeof('a',[1,Inf])}
The code generator creates the executable
writeGreeting.exein the working folder.To run the executable in MATLAB on a Windows platform, enter this command in the Command Window:
system('writeGreeting World')The executable creates
greeting.txtin the current folder containing the textHello, World!.
For more information about specifying string and character vector input types, see Specify String Scalar Inputs at the Command Line.
Specifying main Functions for C/C++ Executables
When you generate an executable, you must provide a main function.
For a C executable, provide a C file, main.c. For a C++ executable,
provide a C++ file, main.cpp. Verify that the folder containing the
main function has only one main file. Otherwise, main.c takes
precedence over main.cpp, which causes an error when generating C++
code. You can specify the main file from the project settings dialog box, the command
line, or the Code Generation dialog box.
By default, when you generate C/C++ source code, static libraries, dynamically linked
libraries, or executables, MATLAB
Coder generates a main function. This generated main function
is a template that you modify for your application. See Incorporate Generated Code Using an Example Main Function. After you copy
and modify the generated main function, you can use it for generation of the C/C++
executable. Alternatively, you can write your own main function.
When you convert a MATLAB function to a C/C++ library function or a C/C++ executable, MATLAB
Coder generates an initialize function and a terminate function. If your file
partitioning method is set to generate one file for each MATLAB file, you must include the terminate header function in
main.c. Otherwise, do not include it in main.c.
For more information about calling the initialize and terminate functions, see Use Generated Initialize and Terminate Functions.
You can specify a main function for an executable by setting the properties of a code configuration object at the command line or by using the Code Generation Settings dialog box in the MATLAB Coder app.
At the Command Line
Set the CustomSource and CustomInclude
properties of the code generation configuration object. The
CustomInclude property indicates the location of C/C++ files
specified by CustomSource.
Create a configuration object for an executable:
cfg = coder.config('exe');Set the
CustomSourceproperty to the name of the C/C++ source file that contains themainfunction. (For more information, see Specifying main Functions for C/C++ Executables.) For example:cfg.CustomSource = 'main.c';Set the
CustomIncludeproperty to the location ofmain.c. For example:cfg.CustomInclude = 'c:\myfiles';Generate the C/C++ executable using the command-line options. For example, if
myFunctiontakes one input parameter of typedouble:codegen -config cfg myMFunction -args {0}
MATLAB Coder compiles and links the main function with the C/C++ code that it generates from
myMFunction.m.
Using the MATLAB Coder App
Set the Output Type, Additional source files, and Additional include directories parameters. The Additional include directories parameter indicates the location of C/C++ files specified by the Additional source files parameter.
To set the output type, on the MATLAB Coder tab of the toolstrip, click Output Type > Executable (.exe).
To open the Code Generation Settings dialog box, on the MATLAB Coder tab of the toolstrip, click Settings.
In the Code Generation Settings dialog box, set the Additional source files to the name of the C/C++ source file that contains the
mainfunction. Set the Additional include directories parameter to the location ofmain.c.To generate the executable, on the MATLAB Coder tab of the toolstrip, click Generate Code and Build.
See Also
codegen | coder.MexCodeConfig | coder.CodeConfig | coder.EmbeddedCodeConfig