Call a C/C++ Static Library Function from MATLAB Code

This example shows how to call a C/C++ library function from MATLAB® code that is suitable for code generation.

Suppose you have a MATLAB file absval.m that contains the following function:

function y = absval(u) %#codegen
  y = abs(u);
end

To generate a C static library function and call it from MATLAB code:

  1. Generate the C library for absval.m.

    codegen -config:lib absval -args {0.0} 

    Here are key points about this command:

    • The -config:lib option instructs MATLAB Coder™ to generate absval as a C static library function.

      The default target language is C. To change the target language to C++, see Specify a Language for Code Generation.

    • MATLAB Coder creates the library absval.lib (or absval.a on Linus Torvalds' Linux®) and header file absval.h in the folder /emcprj/rtwlib/absval. It also generates the functions absval_initialize and absval_terminate in the C library.

    • The -args option specifies the class, size, and complexity of the primary function input u by example, as described in Define Input Properties by Example at the Command Line.

  2. Write a MATLAB function to call the generated library:

    %#codegen
    function y = callabsval
    
    % Call the initialize function before
    % calling the C function for the first time
    coder.ceval('absval_initialize');
    
    y = -2.75;
    y = coder.ceval('absval',y);
    
    % Call the terminate function after 
    % calling the C function for the last time
    coder.ceval('absval_terminate');
    The MATLAB function callabsval uses the interface coder.ceval to call the generated C functions absval_initialize, absval, and absval_terminate. You must use this function to call C functions from generated code. For more information, see Call Generated C/C++ Functions.

  3. Convert the code in callabsval.m to a MEX function so that you can call the C library function absval directly from the MATLAB prompt.

    1. Generate the MEX function using codegen as follows:

      • Create a code generation configuration object for a MEX function:

        cfg = coder.config

      • On Microsoft® Windows® platforms, use this command:

        codegen -config cfg callabsval codegen/lib/absval/absval.lib codegen/lib/absval/absval.h
        By default, this command creates, in the current folder, a MEX function named callabsval_mex

        On the Linus Torvalds' Linux platform, use this command:

        codegen -config cfg  callabsval codegen/lib/absval/absval.a codegen/lib/absval/absval.h

    2. At the MATLAB prompt, call the C library by running the MEX function. For example, on Windows:

      callabsval_mex

Was this topic helpful?