__attribute__((constructor)) 保证被调用一次吗? [英] Is __attribute__((constructor)) guaranteed to be called exactly once?
问题描述
使用__attribute__((constructor))
和__attribute__((destructor))
定义的GCC 共享库构造函数和析构函数是否保证只运行一次?文档似乎暗示它们将至少运行一次,但没有提到不止一次.
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;
}
推荐答案
如果有人想在头文件中使用这样的函数,一个可能有用的观察:如果一个函数被定义为
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()
{ ... }
在 N 个翻译单元中,它会被调用 N 次.
in N translation units, it will be called N times.
这篇关于__attribute__((constructor)) 保证被调用一次吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!