-
Notifications
You must be signed in to change notification settings - Fork 3
Importance of Variable Scope
For a general overview of variable scope in C, see C Scope Rules. Variable scope is especially important to understand when injecting code into SSBM, because scope means more in this context than in a typical program.
char global_array[100] = {0};
static char global_array_static[100];
void foo()
{
char local_array[100];
}
Each of these 3 arrays are 100 bytes, but they exist in different places in memory. local_array is created on the stack when foo is called, and as such it is destroyed when it goes out of scope after foo returns. global_array and global_array_static do not exist on the stack, in fact they aren't even created at run time. These variables are created at compile time and live in the data section of the executable created by compiling this code. An example might look like this:
u32 global_int = 1;
void _main() {...}
and in our executable we would have a section:
80197ad0 <global_int>:
80197ad0: 00 00 00 01 .long 0x1
This means that global_int is placed at address 80197ad0 in RAM and occupies 4 bytes of memory. wiimake will inject this default value and respect the size of the variable when figuring out the address of each section. This means that global_int will always be available for your code to access (assuming the memory regions you provided to wiimake are not touched by the game). In our original example, this means global_array will use up 100 bytes of memory from your available regions and it can be accessed by any part of your code at all times.
So what is the difference between global_array_static and global_array? Besides the differences in how the compiler treats static varibles they will also be initialized slightly differently. global_array_static will always take up 100 bytes in the executable, but global_array will only take up space if it initialized to some value. See the debugging section for more information on how this can create diabolical bugs.