1

I use poco classloader to dynmic loading .so lib. I found that it use a static struct to register the classname to another static variable.

  struct ProxyExec ## UniqueID \
  { \
    typedef  Derived _derived; \
    typedef  Base _base; \
    ProxyExec ## UniqueID() \
    { \
      class_loader::impl::registerPlugin<_derived, _base>(#Derived, #Base); \
    } \
  }; \
  static ProxyExec ## UniqueID g_register_plugin_ ## UniqueID; \

when does the g_register_plugin_ ## UniqueID start executing the constructor, Is it when the .so library is dynamically loaded?

JaMiT
  • 14,422
  • 4
  • 15
  • 31
daohu527
  • 452
  • 4
  • 15
  • yes,`g_register_plugin_ ## UniqueID` cause the constructor and when did it start the constructor, I see some doc said static variable will init before the `main` func – daohu527 Oct 25 '20 at 13:12
  • You have focused on one question, which is good. Before I vote to re-open, though, are you asking the same thing as [When are static and global variables initialized?](https://stackoverflow.com/questions/17783210) If not, could you clarify how your question is different? – JaMiT Oct 25 '20 at 20:59
  • @JaMiT Thanks for you advice! I saw the ref link and it's really help, my question is now focused on `dynmic loading` when static variable will init. – daohu527 Oct 26 '20 at 01:09

1 Answers1

0

I found the static variables are initialized before the main function.

The ELF file have .init and fini sections, when load the library it will first do init progress then transfer control to the main function.

dlopen man doc

The obsolete symbols _init() and _fini()

The linker recognizes special symbols _init and _fini. If a dynamic library exports a routine named _init(), then that code is executed after the loading, before dlopen() returns. If the dynamic library exports a routine named _fini(), then that routine is called just before the library is unloaded. In case you need to avoid linking against the system startup files, this can be done by using the gcc(1) -nostartfiles command-line option.

daohu527
  • 452
  • 4
  • 15