Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 578
ptomato Avatar asked Aug 28 '14 00:08

ptomato


1 Answers

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.

like image 118
Evg Avatar answered Sep 30 '22 16:09

Evg