Showing posts with label static data member. Show all posts
Showing posts with label static data member. Show all posts

October 29, 2011

Static/global variable and shared library behaviour

[Note : This would be a very long discussion and reader would need considerable amount of time to complete the reading]

Problem Description
Let's take an example of a class having a static variable or a global variable.  

Header file : x.h
extern int g_s;

class XYZ
{
        static int s;
    
    private:
        static int getInt();
};
Implementation file:x.cpp


int XYZ::s = 777;
int g_s = 7;
int XYZ::getInt()
{
  return s;
}

Now let us go through below questions (Little Quiz) and answer them
  • What is the scope of global variable (g_s) and static class variable (XYZ::s)? 
    • Naturally, the answer would be global. 
    • For class static data member variable, the scope would be global with additional limitation of privilage (i.e all objects belonging to XYZ in the executable will have only one copy of s and only accessible for class interface).
  • How many copies of the variable exists? 
    • One 
Are the above answers really correct? What happens in case of executable involving multiple shared libraries (so's) - each having object files of x (i.e x.o)? 
We will explore these and come back questions (Little Quiz) and re-answer them in the end.

Description

Consider that you are building and executable a.exe.
Now this executable consists of many objects and libraries - as shown in below diagram.




  1. libXYZ.so consists of 3 objects X.o, Y.o and Z.o 
  2. libVWX.so consists of 3 objects V.o, W.o and X.o 
  3. libWXY.so consists of 3 objects W.o, X.o and Y.o 
  4. and, the executable a.exe consists of  
    1. objects X.o, M.o and A.o and  
    2. shared libraries (linked using -L/-l option in make file) libXYZ.so, libVWX.so and libWXY.so. 
From the diagram,you can see that there are 4 copies of the x.o present in the final executable (represented by 4 copies of x.o object). Thus in the final executable, there are 4 copies of the static variable X::s in the system.
  • Does Building the executable like the above throw linker error during compilation (complaining of multiple definitions)? 
    • Surprisingly No!!!. From a detailed study I have done, the multiple definition is determined based on certain rule set - described below.
    • If the same symbol is found among the peers of objects and/or static library then it is flagged as error during compilation.For example
      • if and only if X.o and M.o contains same symbol, then it is flagged as an error - in case of bulding executable.
      • if and only if X.o and Y.o contains same symbol, then it is flagged as an error - in case of bulding a shared library.   
    •  During linking (last stage of execution building), the shared library symbols are not resolved. That means, linker will not go into the symbol definitions present in any of the linker - in case it is already present in the object file of the executable.
  • Now let us come to the most interesting fact, In such circumstances, which symbol is used? 
    • It depends on the OS. 
        SUSE 10 Linux: 
        Here, the first encountered symbol is always placed in the Global Symbol Table (GST).
        So during execution symbol resolution from any of the library, the GST is dipped into and     would always gets the first symbol - leading to always pointing to same copy of the variable. 

        HP-UX:
        Here, when the execution flows through a library, it would refer to its "global" variable in the scope of its library. This can be visualized as GST containing global variable with the resolution of the library name also.
 
       This is contrary to SUSE Linux.
         

In short, SUSE Linux seems to have a single copy of reference for the global variable across all the libraries, overlapping objects in the executable. However, HPUX seems to have global copy for each library and it would be referenced during the execution. 
  • Doesn't it lead to different kind of behavior in both SUSE and HPUX OS for the same machine?
    • Yes, Try it out!!!

  • How to avoid this kind of problem? 
    • The main problem in this example, is the use of global objects/static global variables in multiple shared libraries and also in the main object file. The general expectation is that the linker to complain the problem - but it does not.
So only other option is to change the libraries into static library and link to the executable, if no error is thrown, relink with shared libraries.
   
Conclusion 

Now let us come back to the little quiz (discussed in the beggining).
  • What is the scope of global variable (g_s) and static class variable (XYZ::s)?
    • (Previous answer)
      • Naturally, the answer would be global. 
      • For class static data member variable, the scope would be global with additional limitation of privilage (i.e all objects belonging to XYZ in the executable will have only one copy of s). 
    • (Now)
      • Global, with the scope of shared library (while building ".so") or executable. 
      • Symbol resolution is done at peer object (.o) or static library (.a).  
      • Recursive symbol resolution is not done among linked shared library to find out conflict resolution.
  • How many copies of the variable exists? 
    • (Previous answer) One 
    • (Now) One per the linkage scope (i.e shared library in this case, or executable for main object file) 
Regards,
Tech Unravel
Supreme Debugging

September 1, 2011

C++ Static data member variable and its initialization

Question
With regard to static data member initialization, as we are all aware of the syntax used in c++, a sample example is provided below


class Account 
{
    public:
        static double rate() { return interestRate; }
        static void rate(double); // sets a new rate
    private:
        static const int period = 30; // interest posted every 30 days
        static double interestRate;
        double daily_tbl[period]; // ok: period is constant expression
};

// define and initialize static class member
double Account::interestRate = initRate();

int main()
{
    Account ac;
    ...
    ...
}


Now here we see two kinds of initialization of static member variable.

a. The const data member variable is initialized at the time of declaration.
b. The non-const data member variable is initialized outside the class declaration.

My initial view was - this is strange!!!
Is it still retained in language because of legacy mistake? Or is there really a need to have such kind of differentiation?

Answer
I did ponder over this question and posted the same in a popular Q&A portal
(stackoverflow).You can find the original question with detailed reply by members here.
 

Let me start re-discussion the same question in a more detailed fashion.

One of the first pointer is ODR (Wikipedia One Definition Rule).
a. This states that any translation unit - a template/type/function or an object can have no more than one definition.since a definition provides the instance, it can be only one in a translation unit. However, declarations can be many.

b. The same argument extends for the exceutable. In an executable, there can be only one definition for a variable (after scope resolution) and function definitions.

This answers the second question. 


  • If non-const static member was allowed to be defined in the class itself,then it would have been impossible to include these class declaration in different translation units. 
  • Thus to avoid violation of ODR rule,the non-const static data member must be defined outside the class declaration.


Now let us come to the first part of the question (which can be explained much more easily), a const data member can be defined inside the class member for two reasons - 
  • Even if multiple copies are present in each translation unit, the expression will be evaluated during compile time and does not violate the ODR theme.
  • A const must be defined during the creation of the instance (Since it cannot be changed later), if not for the above rule, there would have been chance to change it on every object instansiation or having different definition in each translation unit.

Take Away's

 
Developers need not remember each language syntax and its subtle changes based on memorizing the scenarios under which error are thrown by compilers.
 

Instead simple interpretation and logical understanding of the constraints that forced to structure the language can be studied and thus understand the syntax by logical interpretation.

Regards,
Tech Unravel,
Supreme Debugging.