问题
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