GNU C 的一大特色就是__attribute__ 机制。attribute 是一个编译指令,可以设置函数属性(Function Attribute )、变量属性(Variable Attribute )和类型属性(Type Attribute )。
attribute 书写特征是:attribute 前后都有两个下划线,并切后面会紧跟一对原括弧,括弧里面是相应的__attribute__ 参数。
若将某一函数的声明中添加 __ attribute__((constructor)) 属性,那么它具有两种运行时机
- 若函数所在源文件被编译为可执行文件,那么该函数可以在main函数执行前被调用
#include <stdio.h>
#include <stdlib.h>
static int * g_count = NULL;
__attribute__((constructor)) void load_file()
{
printf("Constructor is called.\n");
}
__attribute__((destructor)) void unload_file()
{
printf("destructor is called.\n");
}
int main()
{
printf ("this is main function\n");
return 0;
}
- 若函数所在源文件被编译为共享库,那么该函数可以在共享库被其它进程显式dlopen或者隐式由操作系统加载时都会优先执行
//process source file
#include <stdio.h>
#include <string.h>
#include <dlfcn.h>
int main(int argc, char **argv)
{
void (*print)();
int (*add)(int, int);
void *handle;
if (argc < 2)
return -1;
handle = dlopen(argv[1], RTLD_LAZY);
if (!handle) {
printf("dlopen failed: %s\n", dlerror());
return -1;
}
print = dlsym(handle, "print");
if (!print) {
printf("dlsym failed: %s\n", dlerror());
return -1;
}
print();
add = dlsym(handle, "add");
if (!add) {
printf("dlsym failed: %s\n", dlerror());
return -1;
}
add(1, 2);
dlclose(handle);
return 0;
}
//libss.so source file
#include <stdio.h>
#include <string.h>
void print()
{
printf("I am print\n");
}
int add(int a, int b)
{
printf("Sum %d and %d is %d\n", a, b, a + b);
return 0;
}
//static void king() __attribute__((constructor(101))); the following is also right
static __attribute__((constructor(101))) void king()
{
printf("I am king\n");
}
gcc -Wall -shared -fPIC -o libss.so libss.c -ldl
gcc -Wall -o udlopen udlopen.c
./udlopen libss.so
I am king
I am print
Sum 1 and 2 is 3
__ attribute__((constructor))的这一特性可以被用在许多场合。比如某个so的功能实现需要预先映射一块共享内存,如果要求所有使用该so的进程在加载时手动去做这一步骤是非常不合理的,此时可以将内存映射实现放在__ attribute__((constructor))属性声明的函数中,这样每次so被加载就会自动完成共享内存的创建映射,对so的使用者完全透明,确实够巧妙!