How can I use a macro from custom C code in code generated by MATLAB Coder R2022b?

I am writing MATLAB code intended for code generation with MATLAB Coder in MATLAB R2022b. I have a "uint8" macro "MYVAL" defined in a C header file “myHeader.h”.
I want to use my macro from "myHeader.h" in the code generated from MATLAB Coder. Is there a way to use my macro in the generated code?

 Réponse acceptée

One way to use a custom macro in generated code is with the "coder.opaque" function. Please see the documentation for this function below:
Using the "coder.opaque" function, you can use a C macro in the default value ("value") argument. For instance, the MATLAB function below sets a variable "x" equal to a macro "MYVAL" defined in a custom header file:
function x = myFunction() %#codegen
x = coder.opaque('uint8', 'MYVAL', 'HeaderFile', '"myHeader.h"');
x = uint8(x);
end
If you generate C code from the above function, the generated function returns “MYVAL”. Please see the generated C function below:
/* Function Definitions */
uint8_T myFunction(void)
{
  return (uint8_T)MYVAL;
}
Please see the attached file "MacroInGeneratedCode.zip" for the files to follow this example.

Plus de réponses (0)

Produits

Version

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by