473,770 Members | 2,171 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Initialization Sequence of Global Varaibles

I know global varaibles should always be avoided. I asked this question
just for deep insight about C++.

If global variables are distributed among different source code files,
what's the initialziation sequence of these varaibles. Say,
Foo g_fooMain in main.cpp;
Foo g_hello in hello.cpp;
Foo g_bye in bye.cpp;
and main.cpp has code
#include "hello.h"
#include "bye.h"

Does C++ defines the sequence? or it is compiler-dependent?

Thanks.
Jul 22 '05 #1
4 2674
Cheng Mo wrote:
I know global varaibles should always be avoided. I asked this question
just for deep insight about C++.

If global variables are distributed among different source code files,
what's the initialziation sequence of these varaibles. Say,
Foo g_fooMain in main.cpp;
Foo g_hello in hello.cpp;
Foo g_bye in bye.cpp;
and main.cpp has code
#include "hello.h"
#include "bye.h"

Does C++ defines the sequence? or it is compiler-dependent?


There is no guaranteed order of initialization of global variables in
different translation units. Within a translation unit, global variables
are initialized in their order of definition.

--
Sumit Rajan <su*********@gm ail.com>
Jul 22 '05 #2
Sumit Rajan wrote:
Cheng Mo wrote:
I know global varaibles should always be avoided. I asked this
question just for deep insight about C++.

If global variables are distributed among different source code files,
what's the initialziation sequence of these varaibles. Say,
Foo g_fooMain in main.cpp;
Foo g_hello in hello.cpp;
Foo g_bye in bye.cpp;
and main.cpp has code
#include "hello.h"
#include "bye.h"

Does C++ defines the sequence? or it is compiler-dependent?

There is no guaranteed order of initialization of global variables in
different translation units. Within a translation unit, global variables
are initialized in their order of definition.


Exactly, if you require a sequence, you can enforce it using static
local variables - e.g.

struct foo
{

static foo & Get()
{
static foo local_static;
return local_static;
}
};
void func()
{
foo & x = foo::Get();

// guarenteed that x refers to a constructed foo object
}

.... note that there may be problems with thread safety in some
implementations . gcc 4.0 will have a fix for this, I'm not sure about
VC++ 2005 though.
Jul 22 '05 #3
> note that there may be problems with thread safety in some
implementation s. gcc 4.0 will have a fix for this, I'm not sure about
VC++ 2005 though.


Does the standard require it to be thread safe?

If not then making it thread safe is really not a fix, it is just a courtesy.

Will the thread safety of such a construct on gcc 4.0 be optional so that one
does not pay for the cost of unnecessary synchronization for single-threaded
programs?
Jul 22 '05 #4
DaKoadMunky wrote:
note that there may be problems with thread safety in some
implementatio ns. gcc 4.0 will have a fix for this, I'm not sure about
VC++ 2005 though.

Does the standard require it to be thread safe?

If not then making it thread safe is really not a fix, it is just a courtesy.


Some people will ague that the standard mentions nothing about threads
and hence it is up to the programmer to make things thread safe.

Some will argue that due to the lack of mentioning anything about
threads, the compiler is required to make certain operations thread safe
if the compiler has any extensions that allow threads.

IMHO, the precedent is that many of the standard C++ types are
implemented in a thread safe way today when they were not in the past.
(e.g. std::string was not thread safe in gcc 2.96 but it has been since
gcc 3.0)

The standard is quite explicit that local static variables must be
constructed once. If your compiler allows any extension that enables
threads, then the compiler must generate code that conforms to the
standard (hence thread safe construction of local static variables).

Will the thread safety of such a construct on gcc 4.0 be optional so that one
does not pay for the cost of unnecessary synchronization for single-threaded
programs?


The gcc-4.0 changes (http://gcc.gnu.org/gcc-4.0/changes.html) says :

- The compiler now uses the library interface specified by
the C++ ABI for thread-safe initialization of function-scope
static variables. Most users should leave this alone, but
embedded programmers may want to disable this by specifying
-fno-threadsafe-statics for a small savings in code size.

It seems that -fno-threadsafe-statics will revert to the old (IMHO buggy
behaviour if you use threads).

Jul 22 '05 #5

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

Similar topics

5
9464
by: Michael McKnerney | last post by:
Hi, It seems I can influence how a base class is initialized beyond the 'normal' manner and I was wondering if someone can tell me why this. Here's my example. class A { public: A(int a=1, int b=1, int c=1) : _a(a), _b(b), _c(c) {}
4
2724
by: DaKoadMunky | last post by:
I was recently looking at some assembly code generated by my compiler. When examining the assembly code associated with constructors I noticed that the dynamic-dispatch mechanism was enabled before member initialization but after base initialization. To speak in implementation details the virtual function table pointer for objects being constructed was set before member initialization but after base initialization. Curiousity then...
4
9619
by: Aniruddha | last post by:
I want to initialize an array of function pointers (global) If I do it like: /* definition of foo_1, foo_2, foo_3 all return void and take no args */ void (* foo) (); foo = foo_1 ; foo = foo_2 ; foo = foo_3 ; I get a compile time error, but if initialized like :
3
22811
by: Rahul Gandhi | last post by:
Hi, Which one preferable with respect to code size of the executable Un-initialised global variables or initialised global variables regards Rahul
1
1639
by: ravinder thakur | last post by:
hi all experts, i am porting a project from c to the c++ framework. during the porting i have encounterd a where i have a static and a global variable with the same name. now what rules c languages uses to reslolve the ambiguity between these two variables with the same names. more specifically what will happen if the both of these varaibles gets included in some compilation unit due to the interdependency between the header files???
5
6780
by: Jesper Schmidt | last post by:
When does CLR performs initialization of static variables in a class library? (1) when the class library is loaded (2) when a static variable is first referenced (3) when... It seems that (1) holds for unmanaged C++ code, but not for managed code. I have class library with both managed and unmanaged static variables that are not referenced by any part of the program. All the
6
2266
by: Christof Warlich | last post by:
Hi, the few lines of code below show different results depending on the compiler version (gcc-2.95 versus gcc-3.3 and later): gcc-2.95 first initializes d (line 9) and then t (line 8), as running the executable yields initialized d X constructor
6
2271
by: dudeja.rajat | last post by:
Hi, I found on the net that there is something called module initialization. Unfortunately, there is not much information for this. However, small the information I found module initialization can be of use to me in my project. I'm currently messing with a problem where I'm keeping my global variables ( or symbols) in a module and the other mdoules in the project acess these global variables.
7
2082
by: Brentt | last post by:
Hi, I know this is a terribly simple question, but the docs seem to be designed for people who probably find a the answer to this question terribly obvious. But its not at all obvious to me. I can't figure out why when I define a function, a variable (specifically a list) that I define and initialize in the argument definitions, will not initialize itself every time its called. So for example, when making a simple list of a counting...
0
9619
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
10260
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
10102
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
10038
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
8933
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...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6712
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
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.