Static variable initialization over a library

前端 未结 3 804
名媛妹妹
名媛妹妹 2020-12-03 15:58

I am working on a factory that will have types added to them, however, if the class is not explicitly instiated in the .exe that is exectured (compile-time), then the type i

相关标签:
3条回答
  • 2020-12-03 16:07

    As a general rule of thumb, an application do not include static or global variables from a library unless they are implicitly or explicitly used by the application.

    There are hundred different ways this can be refactored. One method could be to place the static variable inside function, and make sure the function is called.

    0 讨论(0)
  • To expand on one of @AProgrammer's excellent suggestions, here is a portable way to guarantee the calling program will reference at least one symbol from the library.

    In the library code declare a global function that returns an int.

    int make_sure_compilation_unit_referenced() { return 0; }
    

    Then in the header for the library declare a static variable that is initialized by calling the global function:

    extern int make_sure_compilation_unit_referenced();
    static int never_actually_used = make_sure_compilation_unit_referenced();
    

    Every compilation unit that includes the header will have a static variable that needs to be initialized by calling a (useless) function in the library.

    This is made a little cleaner if your library has its own namespace encapsulating both of the definitions, then there's less chance of name collisions between the bogus function in your library with other libraries, or of the static variable with other variables in the compilation unit(s) that include the header.

    0 讨论(0)
  • 2020-12-03 16:23

    When you are linking with a static library, you are in fact extracting from it the object files which provide symbols which are currently used but not defined. In the pattern that you are using, there is probably no undefined symbols provided by the object file which contains the static variable which triggers registration.

    Solutions:

    • use explicit registration
    • have somehow an undefined symbol provided by the compilation unit
      • use the linker arguments to add your static variables as a undefined symbols
      • something useful, but this is often not natural
      • a dummy one, well it is not natural if it is provided by the main program, as a linker argument it main be easier than using the mangled name of the static variable
    • use a linker argument stating that all the objects of a library have to be included
    • dynamic libraries are fully imported, thus don't have that problem
    0 讨论(0)
提交回复
热议问题