Build a Standalone C Library from a MATLAB Function
Generate standalone C code from a MATLAB function, declare input types, verify numerically, and handle unsupported features.
26 Jan 2026, 12:17 UTC

Problem: run a MATLAB algorithm on a system without MATLAB
You have a MATLAB function that produces correct results in the desktop environment, but the deployment target has no MATLAB license—an embedded controller, a C/C++ application, or a production server. Rewriting the algorithm by hand is slow and risks numerical drift.
Useful takeaway
MATLAB Coder can translate a supported MATLAB entry-point function into standalone C or C++ source code. The translation covers only the code-generation subset of MATLAB, and every input must have a declared size, class, and complexity. This guide shows how to generate, inspect, build, and verify the output for one function, with release-specific caveats noted where they apply.
Desired outcome
Generate standalone C source files from a MATLAB function, optionally compile them with a system compiler, and confirm that the generated code reproduces MATLAB results within an application-defined tolerance for representative inputs.
Prerequisites
- A MATLAB installation licensed for MATLAB Coder. Run
verin the MATLAB Command Window and confirm MATLAB Coder appears in the product list. - An entry-point function saved as a
.mfile that uses code-generation-supported MATLAB features. - A compatible C or C++ compiler for the target operating system. Check the default compiler with
mex -setup Cormex -setup C++in MATLAB. - Write permission in the current working folder, because
codegencreates acodegensubdirectory there.
Where to run: MATLAB Command Window or MATLAB Editor. Required permissions: write access to the working folder. Administrator rights are not normally required unless the compiler installation is restricted.
Write a code-generation-ready entry-point function
Add the %#codegen directive to the function file. This directive asks the MATLAB analyzer to check the file for code-generation compatibility. It does not guarantee success; it only enables static checks before you run codegen.
function corrected = applyCalibration(raw) %#codegen
%APPLYCALIBRATION Apply gain and bias to a raw sensor reading.
% corrected = applyCalibration(raw) returns gain .* raw + bias.
% raw is a real double vector of up to 1000 elements.
gain = 2.5;
bias = 1.0;
corrected = gain * raw + bias;
end
This function uses elementary arithmetic on a numeric vector. MATLAB Coder generally supports this subset, but supported features vary by MATLAB release.
Declare input types and run code generation
MATLAB Coder must know the size, class, and complexity of every input before generating C types. You can pass example values or use coder.typeof. The example below declares a real double row vector with a fixed length of 100 and an upper bound of 1000 elements.
% Configuration for a standalone C library
cfg = coder.config('lib');
cfg.TargetLang = 'C';
cfg.GenerateReport = true;
% Input type: real double, row vector, fixed size 100, variable up to 1000
inputType = coder.typeof(0, [1 100], [0 1]);
% Run code generation
codegen applyCalibration -config cfg -args {inputType} -report
Run these commands in the MATLAB Command Window. Replace applyCalibration with your function file name. Adjust the dimensions to match the maximum input size your application expects.
Expected check: codegen returns to the prompt without red error messages and creates a codegen subfolder. Risk: if the function changes array size in a way the analyzer cannot bound, generation fails or produces code that relies on dynamic memory allocation. Unsupported functions or language constructs also cause errors.
Inspect the generated output
Successful generation creates a folder such as codegen/lib/applyCalibration/. It typically contains C source and header files, an HTML code generation report, and build files. Open the HTML report to see which MATLAB lines mapped to C lines and to identify unsupported constructs. The exact folder contents depend on the MATLAB release and configuration.
Build and verify the generated code
The generated source is not automatically an executable or library. Compile it with the target compiler for your deployment platform. MATLAB Coder can generate a makefile, or you can compile the files manually with the system toolchain.
For a quick numerical check without leaving MATLAB, generate a MEX function instead:
codegen applyCalibration -args {zeros(1,100)} -report
Then compare MATLAB and MEX outputs for identical inputs:
raw = rand(1, 50);
matlabOut = applyCalibration(raw);
mexOut = applyCalibration_mex(raw);
maxDiff = max(abs(matlabOut - mexOut));
Practical check: maxDiff should be small relative to your signal range. For simple double-precision arithmetic, differences are often near round-off level, but the exact value depends on the MATLAB release, inputs, and hardware. Choose a tolerance appropriate to your application rather than assuming a fixed threshold.
For standalone deployment, compile the files in codegen/lib/applyCalibration/ with your system compiler and run the same tolerance comparison against the compiled executable or library using representative and edge-case inputs such as empty arrays, maximum-size inputs, and negative values.
Expected checks
codegencompletes without errors.- The
codegenoutput folder contains.cand.hfiles plus an HTML report. - The MEX version reproduces MATLAB output within your chosen tolerance for representative inputs.
- The standalone build completes with the target compiler and produces no unresolved symbols.
Recovery options and limitations
- Unsupported function: replace it with a code-generation-supported equivalent.
coder.extrinsiclets generated code call a MATLAB function, but the result still requires MATLAB or MATLAB Runtime, so it is not truly standalone. - Unbounded array growth: preallocate with a fixed maximum size or use
coder.varsizeto declare bounded variable-size arrays. - Too many unsupported features: keep the algorithm in MATLAB and distribute it with MATLAB Compiler and MATLAB Runtime instead of MATLAB Coder.
- Generated code is not automatically faster. Measure execution time on the target hardware before assuming a performance gain.
- Redistributing generated code may involve license or runtime obligations that depend on your MATLAB release and target environment. Review your license terms before shipping generated code.
Rollback
codegen only writes files under the codegen subfolder in the current directory, plus any generated MEX files. To undo, delete the codegen folder and any generated MEX files such as applyCalibration_mex.mex*. No MATLAB preferences or system settings are changed.
Version-sensitive behavior
The set of supported MATLAB functions, language features, and compatible compiler versions changes by release. Behavior in one MATLAB version may not transfer to another. Confirm compiler support and code-generation feature coverage in the release notes or product documentation for your installed MATLAB version before relying on a specific construct.
Practical verification
After generating code, run the original MATLAB function and the compiled output over edge-case inputs and compare results with an application-appropriate tolerance. If all checks pass, the generated code is a faithful standalone translation of that function for the tested inputs. Re-verify after any MATLAB release upgrade or compiler change.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.