Avoid reuse of local variables in Embedded coder
Show older comments
I'm generating code for an m-function in the simulink enviroment which solves an MPC algorithm. When the C-code is generated, some variables are used multiple times in the generated code, in different contexts. This behaviour breaks down my algorithm, and the resulting C-code does not produce the desired output (in this particular case, it does not produce an output at all). I have seen that using 'config.PreserveVariableNames = "UserNames"' produce code which does not modify the local variables. However, the configuration has to be applied using the codegen command. I have tried to pass this configuration to simulink without luck. Is there a way to tell the Embedded Coder to not modify the local variables in the m-function when generating code from Simulink?
Answers (1)
Fangjun Jiang
on 10 Dec 2024
Edited: Fangjun Jiang
on 10 Dec 2024
0 votes
That is probably not the correct option. You should try to disable the "Reuse local block outputs" option.
There is a "PreserveName" option in Simulink Coder but it is reserved by the Mathworks. https://www.mathworks.com/help/rtw/ref/code-generation-pane-general.html
5 Comments
Felipe Herrera
on 11 Dec 2024
Fangjun Jiang
on 11 Dec 2024
Edited: Fangjun Jiang
on 11 Dec 2024
Okay. It seems that even though you are generating code in Simulink, the MATLAB Function block uses MATLAB Coder to generate code. This quote is from doc "The MATLAB Function block uses the same infrastructure as MATLAB Coder, which you use to generate C/C++ code from MATLAB code outside of Simulink."
So you could open the MATLAB Coder App alone and try to generate code for your function first. Along the way, there is a setting you can choose for "Preserve Variable Names". Compare this code with the code generated from Simulink.
Then, when you generate code in Simulink using Embedded Coder, you can follow this page. There is an option for "PreserveVariableNames".
"Preserve variable names" and "Do not re-use variable names" are two different things, but if the original M-code doesn't re-use variable names, then I assume the generated C code won't re-use variable names when "PreserveVariableNames" is set as "UserNames".
Felipe Herrera
on 12 Dec 2024
Fangjun Jiang
on 13 Dec 2024
Yes. Controlling the code generation exactly as what you want regarding number of files, variable names etc. is sometimes difficult. I would think your best shot is still using the MATLAB Function block in Simulink and generating code as a whole from Simulink. Did you try that "PreserveVariableNames" in the embedded coder configuration? https://www.mathworks.com/help/coder/ref/coder.embeddedcodeconfig.html
Contact the Mathworks tech support for direct assistance.
Felipe Herrera
on 13 Dec 2024
Categories
Find more on Simulink Coder in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!