wiki
wiki

Reputation: 47

Does C++ static member variable has different instance in a single process?

Let us consider a C++ class with one static member variable and two static methods like :

ABC.h

class ABC
{
  private:
    static int val;

  public:
    static void set_val(int v);
    static int  get_val();
};

ABC.cpp

    int ABC::val = 0;
    
    void ABC::set_val(int v) {
          val = v;
    }
    
    int  ABC::get_val() {
         return val;
    }

The Class is defined and implemented in a static library : libabc.a.

I made an executable object file which links test.o and libabc.a.

My question is, when I called ABC::set_val(10) in test.o and called another function, abc_func(), in libabc.a;
abc_func() called ABC::get_val() and got a 0.

Why is ABC::val not 10?

I thought the scope of a static member variable is the whole process.

I printed the address of ABC::val and got 2 different addresses in the functions belonging to test.o and libabc.a.

Why? I thought test.o and libabc.a are in the same process, hence the static member variable address should be the same.

Can anyone explain this?

Upvotes: 3

Views: 269

Answers (2)

wiki
wiki

Reputation: 47

I found the root cause... My makefile are complicated and libabc.a has been linked twice... After I fixed it, ABC::val only has single instance.

Upvotes: 0

Caleth
Caleth

Reputation: 63039

You are violating the One Definition Rule, abetted by a non-standard compiler. Before C++17 you can't have an definition of your static data member within the class definition, and after C++17 you have to define it with the inline specifier.

Violating the ODR means your program is ill-formed, no diagnostic required. I.e. the compiler and linker are not required to emit an error for your program, and the rules of C++ say that it can have any meaning. It looks like your implementation chose to behave as if there were two separate ABC::val objects.

Upvotes: 5

Related Questions