MATLAB: How to build C++ in Simulink Realtime

c/c++simulink

Hello,
I have a C++ project that previosly developed in linux environment.
But suddenly, I need to implement this project in Simulink Realtime now.
I'm totally new to this, so I need a help.
I'm looking for some examples that I can refer to, but there seem too many ways to integrate C/C++ and Matlab.(e.g. mex, legacy_code, S-functions)
What are the differences between them? and What should I choose then?

Best Answer

For Simulink Realtime you need a Simulink model. There are either the C-caller block, legacy code, or S-functions to execute code (https://mathworks.com/help/simulink/implement_algorithms_c-code.html). Since you are using C++, only the level 2 S-functions (https://mathworks.com/help/simulink/c-c-s-functions.html) or legacy code (https://mathworks.com/help/simulink/sfg/integrating-existing-c-functions-into-simulink-models-with-the-legacy-code-tool.html) are left over from the variants. The legacy code tool actually only puts an S-function around C/C++ functions.
I would recommend S-functions because you can optimize your code there and you don't have to rely on the output of the Legacy Code Tool. You should implement the method mdlRTW (https://mathworks.com/help/simulink/sfg/mdlrtw.html) in the S-function and also create a corresponding TLC file. That means you have to write the code once in the S-function and once in the TLC file. In the TLC file you can do a lot of code optimization, so that a lot of overhead disappears when compiling.
Related Question