Two things I would like to know about how static locales are implemented by the compiler

These are two questions about static locales that have always bothered me and I haven't found a definitive answer to:

Question 1:

 struct Test
 {
  static inline const char* name()
  {
     static const char* nameValue = "Name of Test";
     return nameValue;
  }
};

      

Since the method is inline, every compiler that calls it must have a copy of that method. But there should only be one instance of a local static variable nameValue

(correct me if I'm wrong). How is this achieved? We have many cases of a generated function, but they all refer to the same static local. Does the compiler contain a global table of static locales associated with each function by name?

Question 2:

 struct Init
 {
   Init() {printf("init created\n");}
  ~Init() {printf("init destroyed\n");}
 };

 struct Test
 {
   static void func()
   {
       static Init init;
   }
 };

      

The static local Init object is created only once the first time the func () function is called. How does the compiler know when is the first call to func ()? Does it support the flag at runtime, is this the first call to this function?

+3


source to share


1 answer


These are really two unrelated questions.

First, there are various solutions. Perhaps the most common are what are called weak symbols. Roughly speaking, the compiler generates an instance with a specific name in each object file that uses the function, while the linker produces duplicates and only stores one in the final program.



In the second case, the usual solution is to generate a boolean variable associated with the object, and check for this when the object enters the scope.

+2


source







All Articles