Rogue Wave Knowledge Base
Search:    
Browse by category:
Knowledgebase | Glossary | Ask a Question |

What is a static initialization problem?

Article ID: 1259
Last updated: 07 Jun, 2012
Revision: 1
print  Print
share  Share
Views: 5910
Posted: 01 Jan, 2000
by --
Updated: 07 Jun, 2012
by Rehme L.

Problem


 What is a static initialization problem and how does it affect an application?




Cause


A static initialization problem arises if there are two objects in two different translation units (object modules) where one is dependent on the other as shown below.

Typical static initialisation problem:

// foo.cpp

std::string s ("foo");

// bar.cpp

extern std::string s;

struct A
{
    A () {
        a_ = s;
    }
    std::string a_;
};

A a;

As the order of initialization of objects 'a' and 's' is not defined by the compiler, this dependency may cause problems trying to access objects before they are initialized.




Action


One can fix the problem by moving all the global objects into one translation unit or by creating a factory method that returns objects created. So, for instance, fix the dependency by creating a factory function that creates a string object:

// foo.cpp

std::string& get_s()
{
 static std::string s ("foo");
 return s;
}

// bar.cpp

extern std::string s;

struct A
{
    A () {
        a_ = get_s();
    }
    std::string a_;
};

A a;

Hence, look at where all the global objects in an application are declared, and, if possible move them into one translation unit or implement a fix as shown here.


This article was:   Helpful | Not helpful Report an issue


Prev     Next
On AIX 5.3, RCB only generates static libs (*.a) and not dynamic...       How to create a single SourcePro threads rollup library?

Others in this category
b Incorrect RCB Compiler & OS Selections in SuSE Linux Enterprise Server (SLES) 9
b SourcePro Static build looking for a shared Standard Library version
b Currency Library fails to build on AIX 5.3 with xlC 8.0.0.15
b SourcePro install problem on Linux platform
b Use Stream Versions to Improve Efficiency or Provide Compatibility
b On AIX 5.3, RCB only generates static libs (*.a) and not dynamic libs (*.so)
b How to create a single SourcePro threads rollup library?
b Display Issues during SourcePro installation
b Problem Installing SourcePro on 64bit Linux