Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between global variables and variables declared in main in ARM C

I've been trying to use C in Keil to write some test code for my TM4C123G, which uses an ARM microcontroller. I have no clue about ARM assembly, but I have written some assembly code for an AVR microcontroller in the past.

Where are the values of the variables stored, if we declare a variable in C as global, as opposed to declaring it in main?

Are there general guidelines as to whether we should declare a variable global as opposed to in main (when it comes to writing C for a microcontroller) ?

like image 627
codingEnthusiast Avatar asked Sep 29 '22 06:09

codingEnthusiast


1 Answers

Globals in ARM cause an offset to be placed in the calling function's "pool" area. In general, each global needs its own offset. If you do decided to use globals, place them into a single structure so that all the variables can be accessed via a singel pool offset.

Variables defined at the function level live on the stack. These, within reason, can be accessed with a simpler offset from the stack register and tend to be a touch more efficient opcode wise, and perhaps cache wise, depending on what kind of system you are using.

When to use either? Outside of the global vs. local holy wars of maintainability, it comes down to what else your code wants to do. If some variable is being used in a ton of places and you don't want to pass it around as a parameter (a sign that perhaps your design needs work...) then a global would be the way to go. If you need to access this variable across multiple assembler packages (that desing thing again...) then perhaps a global is also fine.

Most of the time though, I would go with local variables. They are much more thread safe, and from a above, tend to be more efficient. They are easier to maintain as well, because there scope is much more confined - which also helps compilers do there jobs better as well.

like image 74
Michael Dorgan Avatar answered Oct 03 '22 04:10

Michael Dorgan