Main Content

Generating Standalone C/C++ Executables from MATLAB Code

Generate a C Executable 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. Using the app, you:

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

  2. Copy and modify the generated main.c and main.h.

  3. Modify the project settings so that the app can find the modified main.c and main.h.

  4. Generate the executable.

Create the Entry-Point Function

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();

Create the Test File

In the same local writable folder, create a MATLAB file, coderand_test.m, that calls coderand.

function y = coderand_test()
y = coderand();

Open the MATLAB Coder app

On the MATLAB Toolstrip Apps tab, under Code Generation, click the MATLAB Coder app icon.

The app opens the Select Source Files page.

Specify Source Files

  1. On the Select Source Files page, type or select the name of the entry-point function coderand.

    The app creates a project with the default name coderand.prj in the current folder.

  2. Click Next to go to the Define Input Types step. The app analyzes the function for coding issues and code generation readiness. If the app identifies issues, it opens the Review Code Generation Readiness page where you can review and fix issues. In this example, because the app does not detect issues, it opens the Define Input Types page.

Define Input Types

Because C uses static typing, at compile time, MATLAB Coder must determine the properties of all variables in the MATLAB files. You must specify the properties of all entry-point function inputs. From the properties of the entry-point function inputs, MATLAB Coder can infer the properties of all variables in the MATLAB files.

In this example, the function coderand does not have inputs.

Click Next to go to the Check for Run-Time Issues step.

Check for Run-Time Issues

The Check for Run-Time Issues step generates a MEX file from your entry-point functions, runs the MEX function, and reports issues. This step is optional. However, it is a best practice to perform this step. You can detect and fix run-time errors that are harder to diagnose in the generated C code.

  1. To open the Check for Run-Time Issues dialog box, click the Check for Issues arrow .

    Select or enter the test file coderand_test.

  2. Click Check for Issues.

    The app generates a MEX function for coderand. It runs the test file replacing calls to coderand with calls to the MEX function. If the app detects issues during the MEX function generation or execution, it provides warning and error messages. Click these messages to navigate to the problematic code and fix the issue. In this example, the app does not detect issues.

  3. Click Next to go to the Generate Code step.

Generate a C main Function

When you generate an executable, you must provide a C/C++ main function. 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.

Before you generate the executable for coderand, generate a main function that calls coderand.

  1. To open the Generate dialog box, click the Generate arrow .

  2. In the Generate dialog box, set Build type to Source Code and Language to C. Use the default values for the other project build configuration settings.

  3. Click More Settings.

  4. On the All Settings tab, under Advanced, verify that Generate example main is set to Generate, but do not compile, an example main function. Click Close.

  5. Click Generate.

    MATLAB Coder generates a main.c file and a main.h file. The app indicates that code generation succeeded.

  6. Click Next to open the Finish Workflow page.

    On the Finish Workflow page, under Generated Output, you see that main.c is in the subfolder coderand\codegen\lib\coderand\examples.

Copy the Generated Example Main Files

Because subsequent code generation can overwrite the generated example files, before you modify these files, copy them to a writable folder outside of the codegen folder. For this example, copy main.c and main.h from the subfolder coderand\codegen\lib\coderand\examples to a writable folder, for example, c:\myfiles.

Modify the Generated Example Main Files

  1. In the folder that contains a copy of the example main files, open main.c.

     Generated main.c

  2. Modify main.c so that it prints the results of a coderand call:

    • In main_coderand, delete the line

      double r;

    • In main_coderand, replace

      r = coderand()
      with
      printf("coderand=%g\n", coderand());

    • For this example, main does not have arguments. In main, delete the lines:

      (void)argc;
      (void)argv;

      Change the definition of main to

      int main()

     Modified main.c

  3. Open main.h

     Generated main.h

  4. Modify main.h:

    • Add stdio to the include files:

      #include <stdio.h>

    • Change the declaration of main to

      extern int main()

 Modified main.h

Generate the Executable

  1. To open the Generate Code page, expand the workflow steps and click Generate

  2. To open the Generate dialog box, click the Generate arrow .

  3. Set Build type to Executable (.exe).

  4. Click More Settings.

  5. On the Custom Code tab, in Additional source files, enter main.c

  6. On the Custom Code tab, in Additional include directories, enter the location of the modified main.c and main.h files. For example, c:\myfiles. Click Close.

  7. To generate the executable, click Generate.

    The app indicates that code generation succeeded.

  8. Click Next to go to the Finish Workflow step.

  9. Under Generated Output, you can see the location of the generated executable coderand.exe.

Run the Executable

To run the executable in MATLAB on a Windows® platform:

system('coderand')

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.

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.

Specify main Functions

Specifying main Functions Using the MATLAB Coder App

  1. To open the Generate dialog box, on the Generate Code page, click the Generate arrow .

  2. Click More Settings.

  3. On the Custom Code tab, set:

    1. Additional source files to the name of the C/C++ source file that contains the main function. For example, main.c. For more information, see Specifying main Functions for C/C++ Executables.

    2. Additional include directories to the location of main.c. For example, c:\myfiles.

Specifying main Functions at the Command Line

Set the CustomSource and CustomInclude properties of the code generation configuration object (see Working with Configuration Objects). 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.