When exactly is gcc __attribute__((constructor)) run?

て烟熏妆下的殇ゞ 提交于 2019-12-05 04:15:15

For ELF files, __attribute__((constructor)) marked functions are ultimately run from the DT_INIT (initialization function) tag. Likewise for __attribute((destructor)) and the DT_FINI (termination function) tag.

Initialization functions are run after relocations are performed, and before returning control to the program, which for program-load-time loaded shared objects means before tranfering control to main(), and for runtime loaded shared objects could probably be interpreted as before returning from dlopen(). Initialization functions from DT_NEEDED shared objects are run before the initialization function in the current shared object.

Termination functions are run from atexit() handlers, after user atexit() handlers. Termination functions are run in reverse order of their corresponding initialization functions.

The ELF standard notes the following:

The dynamic linker ensures that it will not execute any initialization or termination functions more than once.

If you are seeing otherwise, then it's a bug.

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