On Wed, 26 Nov 2003 21:32:53 +1030, "A" <A@iprimus.com.au> wrote in
comp.lang.c++:
Hi,
Consider this code:
//Header File - Foo.h
int i = 0; // non-static global variable
Actually, i is defined without the static keyword, but it is indeed a
static object, meaning that is has static storage duration.
class Foo{
...
};
The scope of i is throughout the entire program since it is global and
No, you are confusing scope with linkage. The definition of i has
namespace scope in C++, and since it is at top level in the global
namespace, it is basically the same as what is called "file scope" in
C, even though that terminology is no longer used in C++.
The definition is in scope from the point where it appears in the
translation unit until the end of the translation unit, although it
may be hidden by another usage of the same name in an inner block.
non-static. Lets say i want to assign a new value to i in another file
called Bar.h, how is it done?
You can only assign a value to an object in code. You can only
initialize an object in its definition. So if i is defined in a
source file, you can't initialize it anywhere else, and you must
assign to it from inside a function, not at file level.
//Header File - Bar.h
i = 1 //like this? or must i use the extern qualifier here? confusion here
is that it i is global then we u need extern to make it external to another
file when it should be already available?
class Bar{
...
};
Regards,
A
You have some confusion over three separate but somewhat related
concepts, scope, linkage, and storage duration. Part of the confusion
stems from the fact that C++ inherited two different meanings of the
"static" keyword from C, not to mention adding another meaning of its
own.
Any object defined outside of a function has static storage duration,
which means it exists for the life of your program. Adding the
keyword "static" or the keyword "const" to such an object does not
change the storage duration, which is still static, and does not
change the scope, which is still to the end of the translation unit,
it merely changes the linkage from internal to external.
External linkage means that code in another translation unit may refer
to the object by name, provided that that code has a suitable external
declaration in its scope.
And the definition of translation unit is basically the source file
you pass to the compiler plus everything it includes.
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
ftp://snurse-l.org/pub/acllc-c++/faq