How can I translate matlab functions to C/C++ void functions using codegen?

6 次查看(过去 30 天)
I would like to know with there is a way to translate matlab functions to C/C++ void functions using codegen. I've tested with a
simple function trying to use -nargout 0 so as to obtain a void function. However, the translated function doesn't behave as the original
one would, since the addition is never executed.
%Matlab function
function soma_a_b = soma(a,b) %#codegen
soma_a_b = a+b;
end
% C code generation at the command line
codegen -c -config:lib soma.m -args {1,2} -nargout 0
%Translated C function
void soma(double a, double b)
{
(void)a;
(void)b;
}
i) Is this expected behavior given that we're passing inputs by value and not returning anything, i.e. not causing any side-effects?
ii) Why are a and b being casted into void?
iii) Is this related to the lack of a return statement in native matlab? Attributing values to the output variables is semantically equivalent to returning, but since the translation output (C code) would have no return maybe the translation mappings get messed up along the way.
iv) Is there a way to force the translated function to be void and execute every instruction properly?

采纳的回答

Mike Hosea
Mike Hosea 2019-4-3
  1. The code generator is usually smart enough to detect when computations have no side effects and have no impact on return values. When it does detect such an occurrence, it elides the code. Your addition is being removed because it had no effect. This "problem" will automatically resolve itself when you write code that does something that changes anything outside the function, whether by returning data to the caller or changing a global variable.
  2. I do not know why the variables are cast to void. I suspect this was done to create a meaningless reference of the input parameters in the C code, possibly to avoid generating code that would lead to warnings with some C compilers. But that is just conjecture on my part.
  3. The return statement in MATLAB is not needed here. If you were to supply one, it would have no effect.
  4. Many functions will translate to (void) C functions, but some parameters will be output or both input and output. If you want a computation to be performed, you will need to make it have some effect. It is difficult to use codegen to create a time-wasting function or something that is just meant to thrash the system without returning anything. Could you supply more information on your use case? Why do you want to compute values that are never used by any other piece of your software system?

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB Coder 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by