pete wrote:
>
CBFalconer wrote:
James Kuyper wrote:
CBFalconer wrote:
...
>>2. What is the effect of making an external (non-local) variable
<<< static?
>>
>Pure foolishness, if non-local means file scope. static here
>prevents exporting the variable.
>
Why is that foolishness? I've used precisely that technique for
encapsulation. File scope variables are something to avoided, in
general. However, when they are justified, in some cases the
dangers of using them can be reduced by declaring them static.
This requires that all functions which refer to the static file
scope variable be defined in the same translation unit, which may
be quite feasible if the number of such functions is small.
Because if it is external it can't be static, or it won't be found.
/* BEGIN new.c */
#include <stdio.h>
static char string[] = "What do you mean?";
int main(void)
{
puts(string);
return 0;
}
/* END new.c */
By "external variable",
I mean an object that was declared in an "external declaration"
and defined in an "external definition",
rather than a variable with external linkage.
I interpreted OP's comment "(non-local)",
to mean that "file scope"
was the definition being used for "external".
N869
6.9 External definitions
Syntax
[#1]
translation-unit:
external-declaration
translation-unit external-declaration
external-declaration:
function-definition
declaration
Constraints
[#2] The storage-class specifiers auto and register shall
not appear in the declaration specifiers in an external
declaration.
[#3] There shall be no more than one external definition for
each identifier declared with internal linkage in a
translation unit. Moreover, if an identifier declared with
internal linkage is used in an expression (other than as a
part of the operand of a sizeof operator), there shall be
exactly one external definition for the identifier in the
translation unit.
Semantics
[#4] As discussed in 5.1.1.1, the unit of program text after
preprocessing is a translation unit, which consists of a
sequence of external declarations. These are described as
``external'' because they appear outside any function (and
hence have file scope). As discussed in 6.7, a declaration
that also causes storage to be reserved for an object or a
function named by the identifier is a definition.
[#5] An external definition is an external declaration that
is also a definition of a function or an object. If an
identifier declared with external linkage is used in an
expression (other than as part of the operand of a sizeof
operator), somewhere in the entire program there shall be
exactly one external definition for the identifier;
otherwise, there shall be no more than one.
--
pete