[Icc-avr] Module globals static?
David Brown
david_brown at hotpop.com
Wed Oct 24 07:33:54 PDT 2007
John Baraclough wrote:
> At 10:45 24/10/2007, you wrote:
>> Bengt Ragnemalm wrote:
>>> Is a variable that is global in a module also automatically static? I
>>> think it is but if so, shouldn't the strictly most correct way to
>>> define the globals also be as static?
>>>
>>
>> Yes, global variables are statically allocated, meaning they have a
>> fixed address in memory (assigned by the linker) and exist throughout
>> the lifetime of the program.
>>
>> You can think of the keyword "static" as having two distinct effects
>> on variables - it ensures that they have a statically allocated
>> address, and it ensures that they have the minimum possible scope.
>> Thus all file-level data and functions should be declared "static"
>> unless you are specifically defining global data or functions that
>> should be available from other files.
>>
>> mvh.,
>>
>> David
>
> Sometimes you need to be careful, as the file scope limiting effect of
> the static keyword can be dangerous. A variable declared as static in
> one file can have an identical name to a static variable in another
> file, but not be at the same address. The linker will know the
> difference but the programmer may not, especially if they are
> maintaining someone else's code.
>
> HTH
>
> John
That is one of the reasons why it is so very important to *always* use
"static" unless you are specifically and intentionally declaring global
data. If two modules written by two different people have variables
called "counter", it is critical that these are separate entities - if
they are not declared static, you've got a disaster on hand. Only let
data (or functions) have global linkage if that's what you really mean -
and that should be clear from matching "extern" declarations in the
header files, and a single definition in one file.
mvh.,
David
More information about the Icc-avr
mailing list