Static variable initialization over a library

一个人想着一个人 提交于 2019-11-27 14:50:39

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!