473,566 Members | 3,186 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Nonlocal Store (global and class static variables)

Hi,

I am reading Stroustrup's book 'C++ Programming Language'. In the
10.4.9 section (Nonlocal Store) he says:

"A variable defined outside any function (that is global, namespace,
and class static variables) is initializated (constructed) before main
is invoked . . ."

.. . .

"No implementation-independent guarantees are made about the order of
construction of nonlocal objects in different complication units . .
.."

So this is wrong:

// foo1.C

int x = 1;

// foo2.C

extern int x;
int y = x;
So when I want initializated a global or class static variable with
other global variable is convenient do it after the main is invoked.

How can I sure that a global variable is initializated before the main
is invoked when I am working with different compilation units?

Thaks,
Jose Luis.
Jul 22 '05 #1
8 2524
"jose luis fernandez diaz" <jo************ **********@yaho o.es> wrote...
I am reading Stroustrup's book 'C++ Programming Language'. In the
10.4.9 section (Nonlocal Store) he says:

"A variable defined outside any function (that is global, namespace,
and class static variables) is initializated (constructed) before main
is invoked . . ."

. . .

"No implementation-independent guarantees are made about the order of
construction of nonlocal objects in different complication units . .
."

So this is wrong:

// foo1.C

int x = 1;

// foo2.C

extern int x;
int y = x;
It's not wrong. Initialisation with zeroes is done at program loading,
but it _might_ work as expected. In any case, you have only two possible
outcomes for the value of 'y': 0 or 1.
So when I want initializated a global or class static variable with
other global variable is convenient do it after the main is invoked.
It wouldn't be "initialisation ". It would be "assignment ".
How can I sure that a global variable is initializated before the main
is invoked when I am working with different compilation units?


They _are_ initialised _before_ main is invoked. Only the _order_ of
their initialisation is undefined.

Put them all in one special compilation unit, "external data".

Victor
Jul 22 '05 #2
"Victor Bazarov" <v.********@com Acast.net> wrote in message news:<8XpJb.264 117$_M.1243853@ attbi_s54>...
"jose luis fernandez diaz" <jo************ **********@yaho o.es> wrote...
I am reading Stroustrup's book 'C++ Programming Language'. In the
10.4.9 section (Nonlocal Store) he says:

"A variable defined outside any function (that is global, namespace,
and class static variables) is initializated (constructed) before main
is invoked . . ."

. . .

"No implementation-independent guarantees are made about the order of
construction of nonlocal objects in different complication units . .
."

So this is wrong:

// foo1.C

int x = 1;

// foo2.C

extern int x;
int y = x;
It's not wrong. Initialisation with zeroes is done at program loading,
but it _might_ work as expected. In any case, you have only two possible
outcomes for the value of 'y': 0 or 1.
So when I want initializated a global or class static variable with
other global variable is convenient do it after the main is invoked.


It wouldn't be "initialisation ". It would be "assignment ".
How can I sure that a global variable is initializated before the main
is invoked when I am working with different compilation units?


They _are_ initialised _before_ main is invoked. Only the _order_ of
their initialisation is undefined.


So, the example above could be wrong because y could be 1 or 0.

Put them all in one special compilation unit, "external data".
Can you give me an example ?. How can I be sure in the example below
that y is always 1 ?

Victor

Jul 22 '05 #3
Put them all in one special compilation unit, "external data".

Can you give me an example ?. How can I be sure in the example below
that y is always 1 ?

Victor

Within one compilation unit initialisation takes place in the order as
written in the file.
So put all your global variables in one cpp-file (or whatever extension
you prefer)
// globals.cpp
int x = 1;
int y = x;
<EOF>

// foo.cpp
extern int x;
....

// bar.cpp
extern int y;
....
This way initialisation takes place in globals.cpp in a well defined
order. Your foo.cpp and bar.cpp files can then use the globals by
declaring them with the extern keyword.

--
Regards,
Christof Krueger

Jul 22 '05 #4
Christof Krueger <ne**@pop2wap.n et> wrote in message news:<bt******* ******@news.t-online.com>...
Put them all in one special compilation unit, "external data".

Can you give me an example ?. How can I be sure in the example below
that y is always 1 ?

Victor

Within one compilation unit initialisation takes place in the order as
written in the file.
So put all your global variables in one cpp-file (or whatever extension
you prefer)
// globals.cpp
int x = 1;
int y = x;
<EOF>

// foo.cpp
extern int x;
...

// bar.cpp
extern int y;
...
This way initialisation takes place in globals.cpp in a well defined
order. Your foo.cpp and bar.cpp files can then use the globals by
declaring them with the extern keyword.


Ok, but what if I design a library. How can I force their users to
initialize the library global variables before their first use ?

// library.C

int x = 1;
// foo1.C

extern int x;
int y = x;
Jul 22 '05 #5
"jose luis fernandez diaz" <jo************ **********@yaho o.es> wrote...
Christof Krueger <ne**@pop2wap.n et> wrote in message

news:<bt******* ******@news.t-online.com>...
>Put them all in one special compilation unit, "external data".
Can you give me an example ?. How can I be sure in the example below
that y is always 1 ?
>Victor

Within one compilation unit initialisation takes place in the order as
written in the file.
So put all your global variables in one cpp-file (or whatever extension
you prefer)
// globals.cpp
int x = 1;
int y = x;
<EOF>

// foo.cpp
extern int x;
...

// bar.cpp
extern int y;
...
This way initialisation takes place in globals.cpp in a well defined
order. Your foo.cpp and bar.cpp files can then use the globals by
declaring them with the extern keyword.


Ok, but what if I design a library. How can I force their users to
initialize the library global variables before their first use ?

// library.C

int x = 1;
// foo1.C

extern int x;
int y = x;


You cannot force the users of your library to do anything. And,
to be entirely frank, it's not a good idea to try. Develop your
library with this thought in mind: the users of it are not dumber
than you, but they may need a bit of guidance from you. So, do
supply your library with a good document describing some features
of your library that are not obvious, or are not features of the
language.

If a C++ programmer does not know that objects with static storage
duration are initialised in unspecified order if they are in two
different compilation units, it's NOT your problem. Besides, the
static objects are really best avoided in any C++ program, just
for that unspecifiedness of the order of their initialisation.

As to the particular question about how to make 'y' to always be
the same as 'x', initialise them _BOTH_ from a function:

// library.C
int x = functionThatRet urnsXValue();
int functionThatRet urnsXValue() {
return 1;
}

// foo1.C
int y = functionThatRet urnsXValue();

And don't let them see the actual 'x'.

Victor
Jul 22 '05 #6
"Victor Bazarov" <v.********@com Acast.net> wrote in message news:<HmYJb.731 281$HS4.5490555 @attbi_s01>...
"jose luis fernandez diaz" <jo************ **********@yaho o.es> wrote...
Christof Krueger <ne**@pop2wap.n et> wrote in message

news:<bt******* ******@news.t-online.com>...
>>Put them all in one special compilation unit, "external data".
>
>
> Can you give me an example ?. How can I be sure in the example below
> that y is always 1 ?
>
>
>>Victor
Within one compilation unit initialisation takes place in the order as
written in the file.
So put all your global variables in one cpp-file (or whatever extension
you prefer)
// globals.cpp
int x = 1;
int y = x;
<EOF>

// foo.cpp
extern int x;
...

// bar.cpp
extern int y;
...
This way initialisation takes place in globals.cpp in a well defined
order. Your foo.cpp and bar.cpp files can then use the globals by
declaring them with the extern keyword.


Ok, but what if I design a library. How can I force their users to
initialize the library global variables before their first use ?

// library.C

int x = 1;
// foo1.C

extern int x;
int y = x;


You cannot force the users of your library to do anything. And,
to be entirely frank, it's not a good idea to try. Develop your
library with this thought in mind: the users of it are not dumber
than you, but they may need a bit of guidance from you. So, do
supply your library with a good document describing some features
of your library that are not obvious, or are not features of the
language.

If a C++ programmer does not know that objects with static storage
duration are initialised in unspecified order if they are in two
different compilation units, it's NOT your problem. Besides, the
static objects are really best avoided in any C++ program, just
for that unspecifiedness of the order of their initialisation.

As to the particular question about how to make 'y' to always be
the same as 'x', initialise them _BOTH_ from a function:

// library.C
int x = functionThatRet urnsXValue();
int functionThatRet urnsXValue() {
return 1;
}

// foo1.C
int y = functionThatRet urnsXValue();

And don't let them see the actual 'x'.

Victor


I am agree with you and thank your hints, but sometimes it is necesary
to use global variables. Stroustup in his book gives an example in
21.5.2 section (Closing of Streams):

". . . how an implementation can ensure that the predefined streams
cout, cin, cerr and clog are cleated before their first use and closed
(only) after their last use . . ."

"The fundamental idea is to define a helper class that is a counter
that keeps track of how many timesn <iostream> has been included in a
separately compiled source file:

class ios_base::Init {
static int count;
public:
Init();
~Init();
};

namespace { ios_base::Init __ioinit; } // in <iostream>, one copy in
each file
// #including <iostream>

int ios_base::Init: :count=0; // in some .C file

Each translation unit declares its own object called __ioinit:

ios_base::Init: :Init() { if (count++==0) { /* initialize cout, cin,
etc. */}

ios_base::Init: :~Init(){ if (count--==0) { //clean up cout, cerr . . .
*/ }
This is a general technique for dealing with libraries that require
initialization an cleanup of global objects . . ."
What do you think about this technique ? Do you know another better or
similar ?

One can write code like this:

ostream my_cout=cout;

#include <iostream>

but he is a fool if do it.

I think that the best is follow your hints whenever possible and like
last resource use a trick similar to the above. What do you think ?

Regards,
Jose Luis
Jul 22 '05 #7
jose luis fernandez diaz skrev i meldingen ...
Hi,

I am reading Stroustrup's book 'C++ Programming Language'. In the
10.4.9 section (Nonlocal Store) he says:

"A variable defined outside any function (that is global, namespace,
and class static variables) is initializated (constructed) before main
is invoked . . ."

. . .

"No implementation-independent guarantees are made about the order of
construction of nonlocal objects in different complication units . .
That is not strictly correct. Variables in a compilation unit U are
initialized before the first call of a function in U.

."

So this is wrong:

// foo1.C

int x = 1;

// foo2.C

extern int x;
int y = x;
Yes.

So when I want initializated a global or class static variable with
other global variable is convenient do it after the main is invoked.
That's one way. But as Victor remarked, it you do that directly it
would be assignment, not initialization. To get initialization you
would have to use dynamic allocation or placement new.
How can I sure that a global variable is initializated before the main
is invoked when I am working with different compilation units?


Very simple: _don't_ use global variables. Instead, if you absolutely
must, you can use global accessor functions for non-public variables.
For example,
extern Foo& fooInstance()
{
static Foo theInstance;
return theInstance;
}
or
static Foo theInstance;

extern Foo& fooInstance(){ return theInstance; }
There are also other solutions.

Jul 22 '05 #8
"jose luis fernandez diaz" <jo************ **********@yaho o.es> wrote...
"Victor Bazarov" <v.********@com Acast.net> wrote in message news:<HmYJb.731 281$HS4.5490555 @attbi_s01>...
"jose luis fernandez diaz" <jo************ **********@yaho o.es> wrote...
Christof Krueger <ne**@pop2wap.n et> wrote in message

news:<bt******* ******@news.t-online.com>...
> >>Put them all in one special compilation unit, "external data".
> >
> >
> > Can you give me an example ?. How can I be sure in the example below > > that y is always 1 ?
> >
> >
> >>Victor
> Within one compilation unit initialisation takes place in the order as > written in the file.
> So put all your global variables in one cpp-file (or whatever extension > you prefer)
>
>
> // globals.cpp
> int x = 1;
> int y = x;
> <EOF>
>
> // foo.cpp
> extern int x;
> ...
>
> // bar.cpp
> extern int y;
> ...
>
>
> This way initialisation takes place in globals.cpp in a well defined
> order. Your foo.cpp and bar.cpp files can then use the globals by
> declaring them with the extern keyword.

Ok, but what if I design a library. How can I force their users to
initialize the library global variables before their first use ?

// library.C

int x = 1;
// foo1.C

extern int x;
int y = x;


You cannot force the users of your library to do anything. And,
to be entirely frank, it's not a good idea to try. Develop your
library with this thought in mind: the users of it are not dumber
than you, but they may need a bit of guidance from you. So, do
supply your library with a good document describing some features
of your library that are not obvious, or are not features of the
language.

If a C++ programmer does not know that objects with static storage
duration are initialised in unspecified order if they are in two
different compilation units, it's NOT your problem. Besides, the
static objects are really best avoided in any C++ program, just
for that unspecifiedness of the order of their initialisation.

As to the particular question about how to make 'y' to always be
the same as 'x', initialise them _BOTH_ from a function:

// library.C
int x = functionThatRet urnsXValue();
int functionThatRet urnsXValue() {
return 1;
}

// foo1.C
int y = functionThatRet urnsXValue();

And don't let them see the actual 'x'.

Victor


I am agree with you and thank your hints, but sometimes it is necesary
to use global variables. Stroustup in his book gives an example in
21.5.2 section (Closing of Streams):

". . . how an implementation can ensure that the predefined streams
cout, cin, cerr and clog are cleated before their first use and closed
(only) after their last use . . ."

"The fundamental idea is to define a helper class that is a counter
that keeps track of how many timesn <iostream> has been included in a
separately compiled source file:

class ios_base::Init {
static int count;
public:
Init();
~Init();
};

namespace { ios_base::Init __ioinit; } // in <iostream>, one copy in
each file
// #including <iostream>

int ios_base::Init: :count=0; // in some .C file

Each translation unit declares its own object called __ioinit:

ios_base::Init: :Init() { if (count++==0) { /* initialize cout, cin,
etc. */}

ios_base::Init: :~Init(){ if (count--==0) { //clean up cout, cerr . . .
*/ }
This is a general technique for dealing with libraries that require
initialization an cleanup of global objects . . ."
What do you think about this technique ? Do you know another better or
similar ?


I think it is generally just what the doctor ordered. Believe you me,
if it comes from somebody like Dr. Stroustrup, you better listen :-)

One can write code like this:

ostream my_cout=cout;
'cout' is undefined here.

#include <iostream>

but he is a fool if do it.

I think that the best is follow your hints whenever possible and like
last resource use a trick similar to the above. What do you think ?


Makes perfect sense to me.

Victor
Jul 22 '05 #9

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

Similar topics

5
3482
by: j | last post by:
Anyone here feel that "global variables" is misleading for variables whose scope is file scope? "global" seems to imply global visibility, while this isn't true for variables whose scope is file scope. If you have a variable whose scope is file scope in another translation unit, you have to provide a local declaration to access that variable...
25
66048
by: Daniel Bass | last post by:
how do i declare a global variable in c#.net? it's like it want's everything in classes... there are times when globals are good, like having constants in a program which apply to several layers/objects/etc... or does it expect me to create a singleton global class structure? surely it's not that terrible.
24
2513
by: LP | last post by:
After a code review one coworker insisted that global are very dangerous. He didn't really give any solid reasons other than, "performance penalties", "hard to maintain", and "dangerous". I think that I am using them appropriate in class in question. One typical example: This class initiates TCP session, keeps sending commands to the server...
25
5134
by: Sahil Malik [MVP] | last post by:
So here's a rather simple question. Say in an ASP.NET application, I wish to share common constants as static variables in global.asax (I know there's web.config bla bla .. but lets just say I wanna use global.asax) --- Would you declare your static var as --- public static int x ;
17
2437
by: Davíð Þórisson | last post by:
now in my web I have some global variables to be used in many different subpages, in the old ASP I simply loaded a variables.asp file into memory using the eval() function. Now I'd like to use XML but what method would I use to load the entries from the xml file into memory and make them quickly accessible globally in the web code? Just need...
15
2456
by: randyr | last post by:
I am developing an asp.net app based on a previous asp application. in the asp applications global.asa file I had several <object id="id" runat="server" scope="scope" class="comclass"> tags for objects that the app used to speed up some global level data access and functionality. I have recoded the class libraries in .net and would like...
8
4853
by: Vishwanathan Raman | last post by:
Hi I have a declared a static DataSet object SOBJ in Global.asax.I also have a localy defined DataSet LSOBJ in Global.asax which I am storing in Application State.Is there any technical differences in the way both the objects are handled by IIS. Are both objects stored in different memory spaces? I can access both the objects in my web...
9
8627
by: CDMAPoster | last post by:
About a year ago there was a thread about the use of global variables in A97: http://groups.google.com/group/comp.databases.ms-access/browse_frm/thread/fedc837a5aeb6157 Best Practices by Kang Su Gatlin, casual mention was made about using static variables as an alternative to using global variables. This caused me to think of the...
1
29323
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have called it polluting the global namespace. This article explores what happens when the global namespace becomes polluted and how to avoid this...
0
7588
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...
0
7903
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. ...
0
8115
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...
0
7959
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6272
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...
0
5216
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3630
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2093
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
1
1205
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.