473,729 Members | 2,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"static" objects and functions

Hello,

I learned that there are five kinds of static objects, namely

1. global objects
2. object defined in namespace scope
3. object declared static instead classes
4. objects declared static inside functions (i.e. local static
objects)
5. objects declared at file scope.

I have seen the examples of (3) and (4) above, can someone please give
me some examples and their purpose for the other types of static
objects?

Moreover, I've seen an extern statement:

class A{...};
extern A a;

which is said to be a definition for static object "a". Why is this a
static object without "static" keyword?

In addition to static objects, there are static functions. I think a
static member function, such as

class A{
static void f();
};
means it doesn't require any instance of A, and can operate on class
A. Is this right? Then I'm wondering if there's any static non-
member function, and if there is, when is it good to use it?

The example "extern A a" above also raises another question. Should I
regard it as a declaration that says there's an object "a" defined in
another source file, or, shall I regard it as a definition, since its
default constructor may be called?

Many thanks,
Jess

May 30 '07 #1
14 6020
>
I learned that there are five kinds of static objects, namely

1. global objects
2. object defined in namespace scope
3. object declared static instead classes
4. objects declared static inside functions (i.e. local static
objects)
5. objects declared at file scope.

I have seen the examples of (3) and (4) above, can someone please give
me some examples and their purpose for the other types of static
objects?
somefile.hxx:
------------

struct A { } ;

extern A object_in_globa l_namespace ;

namespace foo {
extern A object_in_foo_n amespace ;
}

struct X
{
static A object_inside_c lass ;
} ;

void function_with_l ocal_static() ;

somefile.cxx:
------------

A object_in_globa l_namespace ;

namespace foo {
A object_in_foo_n amespace ;
}

A X::object_insid e_class ;

void function_with_l ocal_static()
{
static A local_static ;
// ...
}

namespace {
A internal_linkag e_object ; // ("file scope" object)
}
>
Moreover, I've seen an extern statement:

class A{...};
extern A a;

which is said to be a definition for static object "a". Why is this a
static object without "static" keyword?
"extern A a" is a *declaration* of a global object. It says, "when
you link, expect to find the definition somewhere." The defintion,
"A a", is placed inside a source file (not a header).

You are placing way too much emphasis on the literal meaning of the
word "static". It has some historical baggage which I will not dive
into. In modern C++, the only use of "static" should be inside class
definitions and inside functions. In the former case, it is used to
differentiate between per-instance and per-class; in the latter case,
it is used to differentiate between automatic storage and persistent
(static) storage.
In addition to static objects, there are static functions. I think a
static member function, such as

class A{
static void f();
};

means it doesn't require any instance of A, and can operate on class
A. Is this right? Then I'm wondering if there's any static non-
member function, and if there is, when is it good to use it?
If you put "static" in front of a regular function, that's deprecated
usage. It originally meant internal linkage, but that's done with
anonymous namespaces now. Don't do that. Again, don't read too much
into the literal meaning of the word.
The example "extern A a" above also raises another question. Should I
regard it as a declaration that says there's an object "a" defined in
another source file, or, shall I regard it as a definition, since its
default constructor may be called?
The former. "extern A a" is a declaration. It does not declare that
the object is constructed with the default constructor. Where it is
defined, it may be constructed with any constructor, e.g., "A a(44)".

May 30 '07 #2
On May 30, 9:38 am, jeffjohnson_al. ..@yahoo.com wrote:
You are placing way too much emphasis on the literal meaning of the
word "static". [...] In the former case, it is used to differentiate
between per-instance and per-class [...]
Argh, I had my mind in ruby mode when I wrote "per-class" (classes in
ruby are singleton objects which hold per-class data). Of course this
is not the case in C++; the storage of static class members is the
regular static storage.
May 30 '07 #3
Hi

je************* **@yahoo.com wrote:
namespace {
A internal_linkag e_object ; // ("file scope" object)
}
[...]
If you put "static" in front of a regular function, that's deprecated
usage. It originally meant internal linkage, but that's done with
anonymous namespaces now. Don't do that. Again, don't read too much
into the literal meaning of the word.
That's incorrect. Names declared in unnamed namespaces still have external
linkage. However, there is no (portable) way to access the named object
from within another translation unit.

Markus

May 30 '07 #4
On May 31, 5:38 am, Markus Moll <m...@rbg.infor matik.tu-darmstadt.de>
wrote:
Hi

jeffjohnson_al. ..@yahoo.com wrote:
namespace {
A internal_linkag e_object ; // ("file scope" object)
}
[...]
If you put "static" in front of a regular function, that's deprecated
usage. It originally meant internal linkage, but that's done with
anonymous namespaces now. Don't do that. Again, don't read too much
into the literal meaning of the word.

That's incorrect. Names declared in unnamed namespaces still have external
linkage. However, there is no (portable) way to access the named object
from within another translation unit.
If it still has external linkage, then why is it not accessible from
another translation unit? I thought "external linkage" means it's
visible outside its own translation unit...

Thanks,
Jess

May 31 '07 #5
On May 31, 8:41 am, Jess <w...@hotmail.c omwrote:
On May 31, 5:38 am, Markus Moll <m...@rbg.infor matik.tu-darmstadt.de>
wrote:
jeffjohnson_al. ..@yahoo.com wrote:
namespace {
A internal_linkag e_object ; // ("file scope" object)
}
[...]
If you put "static" in front of a regular function, that's deprecated
usage. It originally meant internal linkage, but that's done with
anonymous namespaces now. Don't do that. Again, don't read too much
into the literal meaning of the word.
That's incorrect. Names declared in unnamed namespaces still have external
linkage. However, there is no (portable) way to access the named object
from within another translation unit.
If it still has external linkage, then why is it not accessible from
another translation unit?
It is, in some very special cases. (It can be used in the
instantiation of an exported template, for example.) Generally,
however, there is no way to name it.
I thought "external linkage" means it's
visible outside its own translation unit...
It is visible, at least conceptually. But since you have no way
to refer to it, it's "visibility " is rather accademic. And of
course, visibility isn't really the word you want. External
linkage means that the same (fully qualified) name in different
translation units refers to the same, single object. When you
write:
namespace { int x ; }
this defines an object with type int and the name <secret>::x.
Any references to <secret>::x, from any translation unit in the
entire program, refer to the same object. The compiler,
however, generates a different <secretfor each translation
unit, and generates it in a way that you cannot even
accidentally hit on it. So about the only way you can refer to
it in another translation unit is when instantiating an exported
template.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 31 '07 #6
jeffjohnson_al. ..@yahoo.com wrote:
I learned that there are five kinds of static objects, namely
1. global objects
2. object defined in namespace scope
3. object declared static instead classes
4. objects declared static inside functions (i.e. local static
objects)
5. objects declared at file scope.
I have seen the examples of (3) and (4) above, can someone please give
me some examples and their purpose for the other types of static
objects?
For some reason, Google won't let me read your original posting,
so I'll answer here...

What do you mean by "static objects": objects declared with the
keyword static, or objects with static lifetime. The two are
only vaguely related, and you can also use the keyword static to
declare functions. For historical reasons, the keyword static
is overloaded, and depending on context, it affects both object
lifetime and linkage. Roughly speaking:

-- At namespace scope, the keyword static means that the symbol
being defined has internal linkage, rather than external
(which is the default at namespace scope). All objects
declared at namespace scope (with or without the keyword
static) have static lifetime. (Lifetime is irrelevant with
regards to functions.)

-- At class scope, static means that the object or function is
independant of any instance of the class. All symbols
declared at class scope have external linkage; objects
declared with static have static lifetime (as opposed to a
lifetime linked to that of the containing instance of the
class type).

-- At local scope, only objects (not functions) can be declared
static; such objects have static lifetime. (All objects
declared at local scope, unless explicitly declared extern,
have no linkage. Functions declared at local scope always
have external linkage.)

With regards to your exact question, I'm not too sure what
you're asking. A "global object" is normally an object declared
and defined in the global namespace without the static keyword,
i.e. an object in namespace scope and with external linkage. By
definition, it can't be declared static (but it always has
static lifetime), because if it were, it wouldn't be a global
object. And there is no "file scope" in C++; if by "file scope"
you mean outside of any namespace, class or function, then that
is "global scope", or the "global namespace".

Note too that the use of static at namespace scope is
deprecated. It is generally preferred to use an anonymous
namespace. (On the other hand, the names of variables declared
"const" have internal linkage, just as if they were declared
static, unless they are explicitly declared "extern".)

As to when you would use them: the classical singleton idiom is
a good example of static used at class scope:

class Singleton
{
public:
static Singleton& instance() ;
// ...
private:
static Singleton* ourInstance ;
} ;

The function instance() can (and will be) called without an
instance of the object, and the variable ourInstance will have
static lifetime, existing before the first instance is created,
and after the last one is destructed.

At local scope, one might use a static variable to keep track of
recursion:

void*
operator new( size_t n )
{
static bool recursing = false ;
void* result = NULL ;
if ( recursing ) {
result = getMemory( n ) ;
} else {
recursing = true ;
std::cerr << "allocating " << n << " bytes at " ;
result = getMemory( n ) ;
std::cerr << result << std::endl ;
recursing = false ;
}
return result ;
}

This is necessary here, since outputting to std::cerr could very
easily end up calling operator new.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 31 '07 #7
On May 31, 8:01 pm, James Kanze <james.ka...@gm ail.comwrote:
jeffjohnson_al. ..@yahoo.com wrote:
I learned that there are five kinds of static objects, namely
1. global objects
2. object defined in namespace scope
3. object declared static instead classes
4. objects declared static inside functions (i.e. local static
objects)
5. objects declared at file scope.
I have seen the examples of (3) and (4) above, can someone please give
me some examples and their purpose for the other types of static
objects?

For some reason, Google won't let me read your original posting,
so I'll answer here...

What do you mean by "static objects": objects declared with the
keyword static, or objects with static lifetime. The two are
only vaguely related, and you can also use the keyword static to
declare functions. For historical reasons, the keyword static
is overloaded, and depending on context, it affects both object
lifetime and linkage. Roughly speaking:

-- At namespace scope, the keyword static means that the symbol
being defined has internal linkage, rather than external
(which is the default at namespace scope). All objects
declared at namespace scope (with or without the keyword
static) have static lifetime. (Lifetime is irrelevant with
regards to functions.)
Many thanks for your answers. :) There're still a few issues that
bother me. Although, as you've said, static under namespace is
deprecated, I feel not so comfortable if I don't completely understand
it. :) If I have

namespace N{
A a;
}

then "a" has external linkage, but if I have

namespace N{
static A a;
}

then "a" has internal linkage, is this right? I think "internal
linkage" means it's only accessible within this current translation
unit, is this also right? Furthermore, I tried one example as
follows:

//test.h
class A{
public:
int x;
A():x(10){}
};

namespace foo{
static extern A b;
}

//test.cpp
#include "test.h"

namespace foo{
A b;
};

//testT.cpp
#include<iostre am>
#include "test.h"

using namespace std;

int main(){
cout << foo::b.x << endl;
return 0;
}

However, the compiler error was

"multiple storage classes in declaration of 'b'"

What does this mean?

-- At class scope, static means that the object or function is
independant of any instance of the class. All symbols
declared at class scope have external linkage; objects
declared with static have static lifetime (as opposed to a
lifetime linked to that of the containing instance of the
class type).

-- At local scope, only objects (not functions) can be declared
static; such objects have static lifetime. (All objects
declared at local scope, unless explicitly declared extern,
have no linkage. Functions declared at local scope always
have external linkage.)
The only local scope that I've seen is within a function body, is
there any other kind of local scope? How can a function be declared
within such local scope? By the way, I think "no linkage" means it is
only accessible within that local scope where it's defined, is this
correct?
With regards to your exact question, I'm not too sure what
you're asking. A "global object" is normally an object declared
and defined in the global namespace without the static keyword,
i.e. an object in namespace scope and with external linkage. By
definition, it can't be declared static (but it always has
static lifetime), because if it were, it wouldn't be a global
object. And there is no "file scope" in C++; if by "file scope"
you mean outside of any namespace, class or function, then that
is "global scope", or the "global namespace".
My interpretation about "global" namespace is that I don't use any
"namespace" to surround my object/function, please correct me if I'm
wrong. Then, why did you say a global object is "an object in
namespace scope and with external linkage"? In other words, do I still
need to use "namespace" to wrap it up?

I got the terms "global objects" and "objects at file scope" from the
book Effective C++. My understanding about them is that a global
object has external linkage (accessible from other translation units),
and a file-scope-object is only accessible within that translation
unit (but not limited to any local scope within that translation
unit). Is this not the intended meaning of the author?
Note too that the use of static at namespace scope is
deprecated. It is generally preferred to use an anonymous
namespace. (On the other hand, the names of variables declared
"const" have internal linkage, just as if they were declared
static, unless they are explicitly declared "extern".)
I tried another example, which also failed to compile.

//test.h
namespace foo{
static extern const int x;
};

//test.cpp
#include "test.h"

namespace foo{
static const int x = 10;
}

#include "test.h"
#include<iostre am>

using namespace std;
int main(){
cout << foo::x << endl;
return 0;
}

However, after I removed the static keyword, it compiled and worked.
Does a const inside a namespace have external or internal linkage?
Moreover, it just seems to me that I can never declare "static" within
a namespace.

Moreover, do all objects that have external linkage have static
lifetime? not a single exception?

Finally, I noticed that sometimes when I declare a static object, I
need "static" keyword, but when I define it, I don't need "static".
Does this depend on the context or, do we not need "static" in general
when we define it?

Thanks very much indeed,
Jess

May 31 '07 #8
On May 31, 8:01 pm, James Kanze <james.ka...@gm ail.comwrote:
jeffjohnson_al. ..@yahoo.com wrote:
I learned that there are five kinds of static objects, namely
1. global objects
2. object defined in namespace scope
3. object declared static instead classes
4. objects declared static inside functions (i.e. local static
objects)
5. objects declared at file scope.
I have seen the examples of (3) and (4) above, can someone please give
me some examples and their purpose for the other types of static
objects?

For some reason, Google won't let me read your original posting,
so I'll answer here...

What do you mean by "static objects": objects declared with the
keyword static, or objects with static lifetime. The two are
only vaguely related, and you can also use the keyword static to
declare functions. For historical reasons, the keyword static
is overloaded, and depending on context, it affects both object
lifetime and linkage. Roughly speaking:

-- At namespace scope, the keyword static means that the symbol
being defined has internal linkage, rather than external
(which is the default at namespace scope). All objects
declared at namespace scope (with or without the keyword
static) have static lifetime. (Lifetime is irrelevant with
regards to functions.)
Many thanks for your answers. :) There're still a few issues that
bother me. Although, as you've said, static under namespace is
deprecated, I feel not so comfortable if I don't completely understand
it. :) If I have

namespace N{
A a;
}

then "a" has external linkage, but if I have

namespace N{
static A a;
}

then "a" has internal linkage, is this right? I think "internal
linkage" means it's only accessible within this current translation
unit, is this also right? Furthermore, I tried one example as
follows:

//test.h
class A{
public:
int x;
A():x(10){}
};

namespace foo{
static extern A b;
}

//test.cpp
#include "test.h"

namespace foo{
A b;
};

//testT.cpp
#include<iostre am>
#include "test.h"

using namespace std;

int main(){
cout << foo::b.x << endl;
return 0;
}

However, the compiler error was

"multiple storage classes in declaration of 'b'"

What does this mean?

-- At class scope, static means that the object or function is
independant of any instance of the class. All symbols
declared at class scope have external linkage; objects
declared with static have static lifetime (as opposed to a
lifetime linked to that of the containing instance of the
class type).

-- At local scope, only objects (not functions) can be declared
static; such objects have static lifetime. (All objects
declared at local scope, unless explicitly declared extern,
have no linkage. Functions declared at local scope always
have external linkage.)
The only local scope that I've seen is within a function body, is
there any other kind of local scope? How can a function be declared
within such local scope? By the way, I think "no linkage" means it is
only accessible within that local scope where it's defined, is this
correct?
With regards to your exact question, I'm not too sure what
you're asking. A "global object" is normally an object declared
and defined in the global namespace without the static keyword,
i.e. an object in namespace scope and with external linkage. By
definition, it can't be declared static (but it always has
static lifetime), because if it were, it wouldn't be a global
object. And there is no "file scope" in C++; if by "file scope"
you mean outside of any namespace, class or function, then that
is "global scope", or the "global namespace".
My interpretation about "global" namespace is that I don't use any
"namespace" to surround my object/function, please correct me if I'm
wrong. Then, why did you say a global object is "an object in
namespace scope and with external linkage"? In other words, do I still
need to use "namespace" to wrap it up?

I got the terms "global objects" and "objects at file scope" from the
book Effective C++. My understanding about them is that a global
object has external linkage (accessible from other translation units),
and a file-scope-object is only accessible within that translation
unit (but not limited to any local scope within that translation
unit). Is this not the intended meaning of the author?
Note too that the use of static at namespace scope is
deprecated. It is generally preferred to use an anonymous
namespace. (On the other hand, the names of variables declared
"const" have internal linkage, just as if they were declared
static, unless they are explicitly declared "extern".)
I tried another example, which also failed to compile.

//test.h
namespace foo{
static extern const int x;
};

//test.cpp
#include "test.h"

namespace foo{
static const int x = 10;
}

#include "test.h"
#include<iostre am>

using namespace std;
int main(){
cout << foo::x << endl;
return 0;
}

However, after I removed the static keyword, it compiled and worked.
Does a const inside a namespace have external or internal linkage?
Moreover, it just seems to me that I can never declare "static" within
a namespace.

Moreover, do all objects that have external linkage have static
lifetime? not a single exception?

Finally, I noticed that sometimes when I declare a static object, I
need "static" keyword, but when I define it, I don't need "static".
Does this depend on the context or, do we not need "static" in general
when we define it?

Thanks very much indeed,
Jess

May 31 '07 #9
On May 31, 4:17 pm, Jess <w...@hotmail.c omwrote:
On May 31, 8:01 pm, James Kanze <james.ka...@gm ail.comwrote:
jeffjohnson_al. ..@yahoo.com wrote:
I learned that there are five kinds of static objects, namely
1. global objects
2. object defined in namespace scope
3. object declared static instead classes
4. objects declared static inside functions (i.e. local static
objects)
5. objects declared at file scope.
I have seen the examples of (3) and (4) above, can someone please give
me some examples and their purpose for the other types of static
objects?
For some reason, Google won't let me read your original posting,
so I'll answer here...
What do you mean by "static objects": objects declared with the
keyword static, or objects with static lifetime. The two are
only vaguely related, and you can also use the keyword static to
declare functions. For historical reasons, the keyword static
is overloaded, and depending on context, it affects both object
lifetime and linkage. Roughly speaking:
-- At namespace scope, the keyword static means that the symbol
being defined has internal linkage, rather than external
(which is the default at namespace scope). All objects
declared at namespace scope (with or without the keyword
static) have static lifetime. (Lifetime is irrelevant with
regards to functions.)
Many thanks for your answers. :) There're still a few issues that
bother me. Although, as you've said, static under namespace is
deprecated, I feel not so comfortable if I don't completely understand
it. :) If I have
namespace N{
A a;
}
then "a" has external linkage, but if I have
namespace N{
static A a;
}
then "a" has internal linkage, is this right?
Correct.
I think "internal linkage" means it's only accessible within
this current translation unit, is this also right?
Not really. Although it's common to think of it in such terms,
linkage is really concerned with whether two (fully qualified)
names refer to the same object (or function, or class, or
whatever). In the above, the fully qualified name is N::a, and
the name is "accessible " in any translation unit which declares
it. In the first case, it has external linkage, which means
that all of the names N::a refer to the same, unique object,
regardless of which translation unit they are in. In the
second, with the static, the name as internal linkage: all of
the declarations within a single translation unit refer to the
same, unique object, but each translation unit has a different
object.
Furthermore, I tried one example as follows:
//test.h
class A{
public:
int x;
A():x(10){}

};
namespace foo{
static extern A b;
Did this compile? It shouldn't: both static and extern are
"storage class specifiers", and "At most one
storage-class-specifier shall appear in a given
decl-specifier-seq."
}
//test.cpp
#include "test.h"
namespace foo{
A b;
};
//testT.cpp
#include<iostre am>
#include "test.h"
using namespace std;
int main(){
cout << foo::b.x << endl;
return 0;
}
However, the compiler error was
"multiple storage classes in declaration of 'b'"
What does this mean?
Exactly what it says. The keywords "auto", "register",
"static", "extern" and "mutable" are storage class specifiers,
and the standard says that at most one can appear in any given
declaration.

Formally, this is a purely syntactic restriction, but the
motivation is that in general, the semantics of each of these
keywords conflict. (One could argue about auto and register, I
suppose.) In this particular case, "static" says that the
variable has internal linkage, and "extern" says that it has
external linkage. Extern also says that it is only a
declaration, and not a definition. The C++ declaration syntax
just grew, and isn't always as coherent or as logical as one
might like. Thus:

namespace A {
int a1 ; // external linkage, definition.
extern int a2 ; // external linkage, declaration.
static int a3 ; // internal linkage, definition.
int const a4 ; // *internal linkage, definition.
extern int const a5 ; // external linkage, declaration.
static int const a6 ; // *internal linkage, definition.
int i1 = 42 ; // external linkage, definition.
extern int i2 = 42 ; // external linkage, definition!
static int i3 = 42 ; // internal linkage, definition.
int const i4 = 42 ; // internal linkage, definition.
extern int const i5 = 42 ; // external linkage, definition.
static int const i6 = 42 ; // internal linkage, definition.
}

The declarations marked * are in fact illegal, as a definition
of a const object is illegal unless the object either has a
non-trivial constructor or an initializer. Note that the table
is full of incoherences and oddities---note in particular the
role of const (which logically is completely orthogonal), and
the fact that an initialization forces the declaration to be a
definition, even if it is extern. (And that to define a const
object with external linkage, you have to use extern.)

Also, these declarations suppose that the object has not been
previously declared. Something like:

namespace A {
static int const x = 42 ;
extern int const x ;
}

is perfectly legal---linkage is established by the first
declaration, and cannot be changed later, and extern only means
external linkage if there has been no previous declaration. On
the other hand, inversing them is not---static means internal
linkage, always, so the linkages conflict.
-- At class scope, static means that the object or function is
independant of any instance of the class. All symbols
declared at class scope have external linkage; objects
declared with static have static lifetime (as opposed to a
lifetime linked to that of the containing instance of the
class type).
-- At local scope, only objects (not functions) can be declared
static; such objects have static lifetime. (All objects
declared at local scope, unless explicitly declared extern,
have no linkage. Functions declared at local scope always
have external linkage.)
The only local scope that I've seen is within a function body, is
there any other kind of local scope?
Local scope is always within a function body, or more exactly, a
compound statement (but a compound statement can only
occur within a function body).
How can a function be declared within such local scope?
void
f()
{
std::vector< int v( std::istream_it erator< int >( file ),
std::istream_it erator< int >() ) ;
}

:-). The problem is more often, how can we ensure that a
definition is not a function declaration in local scope; in the
above, the programmer probably wanted to define a local variable
v, using the two iterator constructor of vector. In fact, he has
declared a function (with external linkage, in global scope)
taking two arguments, and istream_iterato r<int>, and a pointer
to a function returning and istream_iterato r<int>, and returning
a vector<int>.

On the other hand, the intent of:

void
f()
{
extern double g( double ) ;
// ...
}

seems quite clear, although it's not the sort of thing one would
encourage.
By the way, I think "no linkage" means it is only accessible
within that local scope where it's defined, is this correct?
No linkage means that no other declaration can refer to the
object in question. For example:

void
f()
{
int a ; // No linkage...
{
int a ; // So this can't be the same variable.
// ...
}
}

There's an interesting (perverse?) example of this in the
standard:

static int i ; // 1.
void g()
{
int i ; // 2. Hides the static 1.
{
extern int i ; // 3.
}
}

The line labeled 3 refers to yet a third object (not defined
here): since the declaration at 2 hides the declaration at 1,
the compiler doesn't "see" it, and since the declaration at 2
has no linkage, the declaration at 3 declares a new object, with
external linkage (different from the object with internal
linkage defined at 1).

(And if you aren't thoroughly confused yet, you should be.)
With regards to your exact question, I'm not too sure what
you're asking. A "global object" is normally an object declared
and defined in the global namespace without the static keyword,
i.e. an object in namespace scope and with external linkage. By
definition, it can't be declared static (but it always has
static lifetime), because if it were, it wouldn't be a global
object. And there is no "file scope" in C++; if by "file scope"
you mean outside of any namespace, class or function, then that
is "global scope", or the "global namespace".
My interpretation about "global" namespace is that I don't use any
"namespace" to surround my object/function, please correct me if I'm
wrong.
Correct. The concept is that the entire translation unit is
encapsulated in an outer namespace, which is called the global
namespace.
Then, why did you say a global object is "an object in
namespace scope and with external linkage"? In other words, do I still
need to use "namespace" to wrap it up?
No. Namespace scope includes objects defined in this imaginary
namespace which encapsulates the entire translation unit. (On
the other hand, it doesn't include built in types, like int.
Which occasionally causes problems when code is counting on
ADL.)
I got the terms "global objects" and "objects at file scope" from the
book Effective C++.
They're frequently used terms. File scope is the term in the C
standard, and was the term in pre-namespace specifications of
C++. Global objects is a pretty good, succinct term for
something which we all understand, even if it has no formal
backing in the standard. (Note too that the original version of
Effective C++ pre-dates namespaces, and that it's entirely
possible that Scott didn't fully update his terminology in later
versions.)
My understanding about them is that a global
object has external linkage (accessible from other translation units),
and a file-scope-object is only accessible within that translation
unit (but not limited to any local scope within that translation
unit). Is this not the intended meaning of the author?
Not at all. First, of course, scope is more or less orthogonal
to linkage: you can declare objects with external linkage in
block scope, and only have the name visible (in that translation
unit) in block scope. Other than that, file-scope is just the
traditional name for global namespace scope, or global scope.
When used in the context of C++, all three mean exactly the same
thing. (Scope and linkage aren't 100% orthogonal, since an
object declared at namespace scope will always have linkage.)
Note too that the use of static at namespace scope is
deprecated. It is generally preferred to use an anonymous
namespace. (On the other hand, the names of variables declared
"const" have internal linkage, just as if they were declared
static, unless they are explicitly declared "extern".)
I tried another example, which also failed to compile.

//test.h
namespace foo{
static extern const int x;
Again, two storage class specifiers aren't allowed.
};
//test.cpp
#include "test.h"
namespace foo{
static const int x = 10;
}
#include "test.h"
#include<iostre am>
using namespace std;
int main(){
cout << foo::x << endl;
return 0;
}
However, after I removed the static keyword, it compiled and
worked.
Because the first declaration established the linkage (as
external). See above. And don't expect consistency:-).
Does a const inside a namespace have external or internal linkage?
Yes:-).

A const at namespace scope has internal linkage by default. It
will have external linkage if either 1) it is declared with the
storage class specifier extern, or 2) there is a previous
declaration of the same object which has external linkage.
Moreover, it just seems to me that I can never declare "static" within
a namespace.
Sure you can:

namespace A {
static int x = 32 ;
}

Do this in several different translation units, and you'll find
that the modifications to x in one are not visible in the other.
Because the x in each translation unit is a different object.
Moreover, do all objects that have external linkage have static
lifetime? not a single exception?
Class members have external linkage, and don't (necessarily) have
static lifetime. What is true is that all objects at namespace
scope have static lifetime, and that all objects declared static
(regardless of their linkage or scope) have static lifetime.
Finally, I noticed that sometimes when I declare a static object, I
need "static" keyword, but when I define it, I don't need "static".
Does this depend on the context or, do we not need "static" in general
when we define it?
No. If their is a previous declaration visible (which has
linkage), the linkage is that of the previous declaration.
(Most of the time, the only declaration of a static variable is
also its definition.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Jun 1 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

29
4400
by: Alexander Mahr | last post by:
Dear Newsgroup, I'm somehow confused with the usage of the static keyword. I can see two function of the keyword static in conjunction with a data member of a class. 1. The data member reffers in all objects of this class to the same data Or in other word by using the static keyword all objects of one class can share data. (This is what I want)
1
1470
by: Harald Deischinger | last post by:
I am using a source file with the following style (I know it is not very beautiful but it is working): SRC1.cpp: static void vFoo() { // bla bla bla } static int iInit1(name, fun) { // access some global variables to register fun as name.
4
2324
by: jr | last post by:
I am working in VC++ so this may be microsoft specific though I don't think so. Excuse me if it is. Assuming it isn't, can someone generally explain the purpose of having both - is it purely a deployment/distribution thing. I notice that the static library generates obj files and a Lib file. Could someone kindly explain how they relate to one another. Thanks very much
12
13463
by: cppaddict | last post by:
Hi, I know that it is illegal in C++ to have a static pure virtual method, but it seems something like this would be useful when the following 2 conditions hold: 1. You know that every one of your Derived classes will need to implement some method, but implement it differently, and that the base class cannot implement it. This is where pure virtual comes in.
3
1384
by: ruud.bos | last post by:
Hi list, As a C++ newbie, I have a question about static member functions. Suppose I have the following class definition: class MyClass { public: static void MyFunc(); };
2
9084
by: Lu | last post by:
Hello, I am wondering how to protect a global variable in a header file from external access. So I googled and found: "The keyword 'static' has two different uses, depending on whether it is applied to an external variable or function or to an automatic variable. When applied to an external variable (global) variable the scope of that variable to the file in which it is declared. This is useful to hide buffers and variables that are used...
9
2308
by: Neil Kiser | last post by:
I'm trying to understand what defining a class as 'static' does for me. Here's an example, because maybe I am thinking about this all wrong: My app will allows the user to control the fonts that the app uses. So I will need to change the fonts depending on what settings the user has entered. However, it seems kind of wasteful to me to go to teh registry, fetch the font information and create new font objects for every form that I am...
3
5855
by: Steve Folly | last post by:
Hi, I had a problem in my code recently which turned out to be the 'the "static initialization order fiasco"' problem (<http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12>) The FAQ section describes a solution using methods returning references to static objects. But consider:
2
11709
by: chenxinleo | last post by:
Hi, When i use some standard library functions and fields,which return char* type(like ctime in time.h, optarg in getopt.h)and do not have to be freed after calling,i always worry about memory leaking(thoug i konw i just donot have to).Then i look inside in time.h file(mingw) ,and i found notes say"These functions write to and return pointers to static buffers that may be overwritten by other function calls".So how is the"static buffers"...
0
8913
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8761
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9280
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8144
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2162
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.