Is LTO allowed to remove unused global object if there is code in a different translation unit relying on side effects of its construction?

后端 未结 3 1073
鱼传尺愫
鱼传尺愫 2021-01-14 22:38

First, just to avoid XY problem: this issue comes from https://github.com/cnjinhao/nana/issues/445#issuecomment-502080177. The library code should probably not do such thing

3条回答
  •  灰色年华
    2021-01-14 23:35

    Since you never reference object from static library in the main executable it is not going to exist unless you link that static library with -Wl,--whole-archive. It is not a good idea to rely on construction of some global objects to perform initialization anyway. So you should just invoke initialize_font explicitly prior to using other functions from that library.

    Additional explanation for question tagged language-lawyer:

    static platform_abstraction object; can not be eliminated in any circumstances according to

    6.6.4.1 Static storage duration [basic.stc.static]
    2 If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 15.8.

    So what is going on here? When linking static library (archive of object files) by default linker will only pick objects files required to fill undefined symbols and since stuff from platform_abstraction.cpp is not used anywhere else linker will completely omit this translation unit. --whole-archive option alters this default behavior by forcing linker to link all the object files from the static library.

提交回复
热议问题