extern "C" __attribute__((constructor))

发布时间 2023-11-05 14:46:14作者: _溯源
  • extern "C":这是 C++ 中的语法,用于指定一个函数或变量应该按照 C 语言的约定进行编译和链接。在 C++ 中,函数和变量的名称会根据其作用域和命名空间进行修饰,而这会导致无法和 C 语言中的函数和变量进行正确的链接。使用 extern "C" 可以避免这个问题,确保这个函数或变量的名称不会被修改。

 

__attribute__ 介绍

__attribute__是一个编译属性,用于向编译器描述特殊的标识、错误检查或高级优化。它是GNU C特色之一,系统中有许多地方使用到。 __attribute__可以设置函数属性(Function Attribute )、变量属性(Variable Attribute )和类型属性(Type Attribute)等。

__attribute__ 格式

1
2
__attribute__ ((attribute-list)) 

__attribute__((constructor))

确保此函数在 在main函数被调用之前调用,iOS中在+load之后main之前执行。 constructordestructor会在ELF文件中添加两个段-.ctors.dtors。当动态库或程序在加载时,会检查是否存在这两个段,如果存在执行对应的代码。

1
2
3
4
5
__attribute__((constructor))
static void beforeMain(void) {
    NSLog(@"beforeMain");
}
1
2
__attribute__((constructor(101))) // 里面的数字越小优先级越高,1 ~ 100 为系统保留

__attribute__((destructor))

1
2
3
4
__attribute__((destructor))
static void afterMain(void) {
    NSLog(@"afterMain");
}

确保此函数在 在main函数被调用之后调

参考文章

extern c __attribute__((visibility( default ))) __attribute__((used))

__attribute__详解及应用