Is __attribute__((constructor)) guaranteed to be called exactly once?

偶尔善良 提交于 2021-01-27 05:20:33

问题


Are GCC shared-library constructors and destructors, defined with __attribute__((constructor)) and __attribute__((destructor)), guaranteed to run exactly once? The documentation seems to imply that they will be run at least once, but doesn't mention anything about more than once.

In other words, if I do an operation in the constructor that must be done only once, do I need to protect it like so:

static gboolean constructor_has_run = FALSE;
if(!constructor_has_run) {
    do_operation();
    constructor_has_run = TRUE;
}

回答1:


If you use __attribute__((constructor)) it will be called at the beginning of the execution.

So you don't have to protect as you have mentioned above.

If you mention too its not wrong

For more Info on __attribute__((constructor)) you can take a look at https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html




回答2:


An observation that might be useful if someone wants to use such functions in headers: if a function is defined like

__attribute__((constructor)) inline void fn()
{ ... }

in N translation units, it will be called N times.



来源:https://stackoverflow.com/questions/25539021/is-attribute-constructor-guaranteed-to-be-called-exactly-once

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