MATLAB: How to have a global variable in a generated code that affects the whole model

codeEmbedded Coderexportedglobalgenerationglobalvariables

How can you have a global variable in the generated code for the top-model that affects the whole model?
In other words, if you change the value in the top-level code, how can this value propagate throughout the model/generated code?

Best Answer

The steps that you would need to follow are:
(1) Go to Model Explorer:
  • Go to Base Workspace
  • Add a Simulink Parameter and name it, for example 'CPG_STK_TING'
  • Set its value and data type
  • Change the storage class to 'ExportedGlobal'
  • Change the Alias to the name you want the variable to have in the .C files (i.e. CPG_STK_TING)
  • Apply
(2) Make sure that all the models (reference models, subsystems, top model etc) have the same configurationSet.
  • Please make sure that the 'Minimize data copies between local and global variables' is unchecked.  
  • You do not have to set the 'ExportedGlobal' Parameter through the optimization settings. This has been done in step (1). 
(3) Set the wanted Sample Time of the top model in the Configuration Parameters. This should propagate throughout the model.
(4) Generate Code
(5) You should see an 'extern real_T CPG_STK_TING' variable in all .h files corresponding to the models that have the CPG_STK_TING variable in them.
(6) The top level .C file should have a line where the CPG_STK_TING value is set. If you change that value, that value should propagate throughout your code.