A local static variable is created several times, why?

I am confused by the result that I get from this code. In one dll, the counter is incremented when the static variable is initialized. Then, when main is executed, I read this counter, but I get 0 instead of 1. Can someone explain this to me?

In my dynamic library project:

// Header file
class Foo {
   int i_ = 0;

   Foo(const Foo&) = delete;
   Foo& operator= (Foo) = delete;

   Foo()
   {
   }

public:
   void inc()
   {
      ++i_;
   }

   int geti()
   {
      return i_;
   }

   static Foo& get()
   {
      static Foo instance_;
      return instance_;
   }

   Foo( Foo&&) = default;
   Foo& operator= (Foo&&) = default;
};

int initialize()
{
   Foo::get().inc();
   return 10;
}

class Bar
{
   static int b_;

};

// cpp file
#include "ClassLocalStatic.h"


int Bar::b_ = initialize();

In my application project

// main.cpp
#include <iostream>

#include "ClassLocalstatic.h"

int main(int argc, const char * argv[])
{
   std::cout << Foo::get().geti();
   return 0;
}
+5
source share
2 answers

Executables and DLLs are going to get their own copy Foo::get(), each of which has its own copy of a static variable. Because they are located in separate linker outputs, the linker cannot consolidate them as usual.

To continue further:

++ , ; , , . . fooobar.com/questions/341188/.... , , , . , , . , , DLL, , .

, Foo::get() DLL.

+8

++ , . , , .

, , ++ : DLL.

++ DLL; , . ++ , .

, , DLL. , .

++ , , ++, DLL, , , .

, DLL, . , , .

- , , extern DLL: DLL . , , a /DLL (__declspec(dllexport)) - /DLL (__declspec(dllimport)).

, DLL. , DLL-, .

+7

All Articles