The function modified with constructor will be executed before the main function is executed, and the priority can be set, and the destructor can be executed after the main function.
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
int g_num;
int getRand(int max)
{
int num = 0;
static int flag = 0;
if(!flag) {
srand((unsigned)time(NULL));
flag = 1;
}
num = rand()%max;
num++;
printf("getRand %d\n",num);
return num;
}
#define printh() printf("in func %s.%d g_num=%d\n",__func__,__LINE__,g_num)
static void __attribute__ ((constructor)) run_before_main_1()
{
printh();
}
static void __attribute__ ((constructor(101))) init1()
{
printh();
}
static void __attribute__ ((constructor(102))) init2()
{
printh();
g_num = getRand(10);
printh();
}
static void __attribute__ ((constructor(103))) init3()
{
printh();
}
static void __attribute__ ((destructor)) run_after_main()
{
printh();
}
static void __attribute__ ((constructor)) run_before_main_2()
{
printh();
}
int main(void)
{
printh();
g_num = 20;
printf("main done!\n");
return 0;
}
operation result
If the priority of destructor is set, it will be executed before main according to the priority of the function modified by constructor
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
int g_num;
int getRand(int max)
{
int num = 0;
static int flag = 0;
if(!flag) {
srand((unsigned)time(NULL));
flag = 1;
}
num = rand()%max;
num++;
printf("getRand %d\n",num);
return num;
}
#define printh() printf("in func %s.%d g_num=%d\n",__func__,__LINE__,g_num)
static void __attribute__ ((constructor)) run_before_main()
{
printh();
}
static void __attribute__ ((constructor(101))) init1()
{
printh();
}
static void __attribute__ ((constructor(102))) init2()
{
printh();
g_num = getRand(10);
printh();
}
static void __attribute__ ((constructor(103))) init3()
{
printh();
}
static void __attribute__ ((destructor)) run_after_main()
{
printh();
}
static void __attribute__ ((constructor(201))) exit_1()
{
printh();
}
static void __attribute__ ((constructor(202))) exit_2()
{
printh();
}
static void __attribute__ ((constructor(203))) exit_3()
{
printh();
}
int main(void)
{
printh();
g_num = 20;
printf("main done!\n");
return 0;
}
operation result