是否__attribute __((构造函数)保证只调用一次?

时间:2014-08-28 00:36:01

标签: c gcc shared-libraries

使用__attribute__((constructor))__attribute__((destructor))定义的GCC共享库构造函数和析构函数是否保证只运行一次?文档似乎暗示它们将至少运行一次,但不会多次提及任何内容。

换句话说,如果我在构造函数中执行必须只执行一次的操作,我是否需要像这样保护它:

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

2 个答案:

答案 0 :(得分:2)

如果使用__attribute__((constructor)),将在执行开始时调用它。

所以你不必像上面提到的那样保护。

如果你提到它没有错误

有关__attribute__((constructor))的更多信息,您可以查看https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

答案 1 :(得分:0)

如果有人想在标头中使用此类函数,则该观察可能会很有用:如果函数定义如下

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

以N个翻译单位为单位,将被称为N次。

相关问题