Is __attribute __ ((constructor)) guaranteed to be called exactly once?

Are the constructors and destructors of the GCC shared library defined with __attribute__((constructor))

and __attribute__((destructor))

guaranteed to run exactly once? The documentation seems to imply that they will run at least once, but they don't mention anything more than once.

In other words, if I am doing an operation in the constructor that needs to be done only once, I need to protect it like this:

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

      

+4


source to share


2 answers


If you use it __attribute__((constructor))

, it will be called at the start of execution.

This way, you don't need to protect as you mentioned above.



If you mentioned too it is not.

For more information on __attribute__((constructor))

you can look at https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

+2


source


An observation that might be helpful if someone wants to use functions like this in headers: if the function is defined as

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

      



in N translation units it will be called N times.

0


source







All Articles