MATLAB: How to partition a C source file which calls several void functions that act on global variables into separate C-MEX S-Function blocks in Simulink 8.0 (R2012b)

simulink

I have a main C source file that has the following structure:
#include "…."
Define global variables
Code
Call to void function1(void)
Code
Call to void function2(void)
I would like to have one S-Function block for function1 and one S-Function block for function2. The difficulty in this is the sharing of global variables between these S-Function blocks. What is the recommended way of implementing this?

Best Answer

Let us assume that the global variables you initially declared are x1, x2, and x3, and func1 and func2 that are called from within main.c have the following implementations:
void func1 (void){
x1++;
x2--;
x3 = x1+x2;
}
void func2 (void){
x1--;
x2++;
x3 = x1-x2;
}
If you would like to create a separate S-Function block for func1 and func2, you would need to create a wrapper function for func1 first. For example,
#include "CustomCode.h" //containing the declarations of the global variables and func1 and func2
Void func1Wrapper (ux1, ux2, ux3, &yx1, &yx2, &yx3)
{
x1 = ux1;
x2=ux2;
x3=ux3;
func1();
(*yx1)=x1;
(*yx2)=x2;
(*yx3)=x3;
}
Once you generate an S-Function block out of func1Wrapper, you could then attach Data Store Read blocks to the inports of this S-Function block, and attach Data Store Write blocks at the outports of this S-Function block. A similar procedure as described above can be used to generate an S-Function block for func2Wrapper which contains a call to func2(). Again, the same Data Store Read and Write blocks can be used for func2Wrapper S-Function.