Main Content

Generating Standalone C/C++ Executables from MATLAB Code

R2026b

Generate 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:

  1. Add the MATLAB function as an entry-point function by using the MATLAB Coder app.

  2. Generate an example C main function that calls the generated library function.

  3. Modify the generated main.c and main.h.

  4. Modify the code generation settings so that the app can find the modified main.c and main.h.

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

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

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

  3. On the MATLAB Coder tab of the toolstrip, click Generate Code. The app generates the files main.c and main.h in the folder codegen/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.

  1. Open main.c.

  2. Modify the main_coderand function so that it prints the results of the coderand call. 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());
    }

  3. For this example, the main function does not have arguments. In the main function, delete these lines:

      (void)argc;
      (void)argv;

    Change the definition of the main function. Delete this line:

    int main(int argc, char **argv)

    Replace the deleted line with this line:

    int main()

  4. Save your changes.

  5. Open main.h

  6. Under the /* Include Files */ comment, add this line:

    #include <stdio.h>

  7. Change the declaration of the main function. Delete this line:

    extern int main(int argc, char **argv);

    Replace the deleted line with this line:

    extern int main();

  8. 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.c in 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.

  1. 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();
  2. Write a main C function, c:\myfiles\main.c, that calls coderand. 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".

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

    codegen generates a C executable, coderand.exe, in the current folder. It generates supporting files in the default folder, codegen/exe/coderand. codegen generates the minimal set of #include statements 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.

  1. 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
  2. Define the input type as a variable-size character vector and generate a static library to produce an example main function:

    cfg = coder.config("lib");
    codegen -config cfg writeGreeting -args {coder.typeof('a',[1,Inf])}

    The code generator produces example main.c and main.h files in the folder codegen/lib/writeGreeting/examples.

  3. Copy the generated main.c and main.h to your working folder. Open main.c and modify it to pass the command-line argument to the entry-point function.

    In the /* Function Declarations */ section, add a forward declaration for the main_writeGreeting function:

    static void main_writeGreeting(const char* str);

    Modify the main_writeGreeting function to accept a const char* argument. Use emxCreateWrapper_char_T to 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 main function, pass argv[1] to the modified main_writeGreeting function:

    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;
    }
  4. Open main.h. Under the /* Include Files */ comment, add:

    #include <stdio.h>
    #include <string.h>

    In the /* Function Declarations */ section, remove the declaration for main_writeGreeting. Because the function is declared static in main.c, it does not need an extern declaration in the header file.

  5. 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.exe in the working folder.

  6. To run the executable in MATLAB on a Windows platform, enter this command in the Command Window:

    system('writeGreeting World')

    The executable creates greeting.txt in the current folder containing the text Hello, 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.

  1. Create a configuration object for an executable:

    cfg = coder.config('exe');
    
  2. Set the CustomSource property to the name of the C/C++ source file that contains the main function. (For more information, see Specifying main Functions for C/C++ Executables.) For example:

    cfg.CustomSource = 'main.c';

  3. Set the CustomInclude property to the location of main.c. For example:

    cfg.CustomInclude = 'c:\myfiles';

  4. Generate the C/C++ executable using the command-line options. For example, if myFunction takes one input parameter of type double:

    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.

  1. To set the output type, on the MATLAB Coder tab of the toolstrip, click Output Type > Executable (.exe).

  2. To open the Code Generation Settings dialog box, on the MATLAB Coder tab of the toolstrip, click Settings.

  3. In the Code Generation Settings dialog box, set the Additional source files to the name of the C/C++ source file that contains the main function. Set the Additional include directories parameter to the location of main.c.

  4. To generate the executable, on the MATLAB Coder tab of the toolstrip, click Generate Code and Build.

See Also

| | |

Topics