I have seen static structure declarations quite often in a driver code I have been asked to modify.
I tried looking for information as to why structs
are declared static and the motivation of doing so.
Can anyone of you please help me understand this?
A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.
The static keyword in C has several effects, depending on the context it's applied to. when applied to a variable declared inside a function, the value of that variable will be preserved between function calls.
Static variables should not be declared inside structure. The reason is C compiler requires the entire structure elements to be placed together (i.e.) memory allocation for structure members should be contiguous.
A structure is used to represent information about something more complicated than a single number, character, or boolean can do (and more complicated than an array of the above data types can do).
The static
keyword in C has several effects, depending on the context it's applied to.
Both usages are pretty common in relatively low-level code like drivers.
The former, and the latter when applied to variables, allow functions to retain a notion of state between calls, which can be very useful, but this can also cause all kinds of nasty problems when the code is being used in any context where it is being used concurrently, either by multiple threads or by multiple callers. If you cannot guarantee that the code will strictly be called in sequence by one "user", you can pass a kind of "context" structure that's being maintained by the caller on each call.
The latter, applied to functions, allows a programmer to make the function invisible from outside of the module, and it MAY be somewhat faster with some compilers for certain architectures because the compiler knows it doesn't have to make the variable/function available outside the module - allowing the function to be inlined for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With