用 _attribute_ 将函数登记到.ctors段 使接口在main之前执行

用 __attribute__ 将函数注册到.ctors段 使接口在main之前执行#include stdio.hvoidmy_init(){printf(H

用 __attribute__ 将函数注册到.ctors段 使接口在main之前执行

#include <stdio.h>

void  my_init()
{
     printf("Hello ");
}

typedef void (*ctor_t)(void);

ctor_t __attribute__ ((section(".ctors"))) my_init_p = my_init;

int main()
{
     printf("world \n");
     return 0;
}

输出:Hello world

 

该程序等同于

 

#include <stdio.h>

void my_init(void) __attribute__ ((constructor));

void  my_init()
{
     printf("Hello ");
}

int main()
{
     printf("world \n");
     return 0;
}