在工程中有多个模块,每个模块功能的自己的初始化函数。如何在程序启动的时候不经过main调用初始化各个模块?
eg:
main.c
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h> //atexit
#include "t.h"
int gTest=0;
void gTest_add()
{
gTest=gTest+1;
}
int main()
{
printf( "\n%d\n",gTest);
return 0;
}
t.h
void gTest_add();
//void before_main(int a, int b);
//必须加 static 限定
static void before_main(int a, int b) __attribute__((constructor));
f.c
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h> //atexit
#include "t.h"
void before_main(int a, int b)
{
printf("before main %s\n", __FILE__);
gTest_add();
}
static __attribute__((destructor)) void after_main1()
{
printf("after main\n");
}
f2.c
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h> //atexit
#include "t.h"
static void before_main(int a, int b)
{
printf("before main %s\n", __FILE__);
gTest_add();
}
static __attribute__((destructor)) void after_main()
{
printf("after main\n");
}
编译:gcc t.c f.c f2.c
执行:./a.out
结果:
[root@localhost workspace]# ./a.out
before main f2.c
before main f.c
2
after main
after main
参考:
http://blog.csdn.net/dengxu11/article/details/6708269
http://www.cnblogs.com/astwish/articles/3460618.html
http://blog.csdn.net/carmazhao/article/details/7169659