Passion/Programming

__attribute__((constructor))

sunshout 2013. 12. 17. 00:01

In a C language, there is a constructor which is loaded in advanced to main() function.


main.c

#include <stdio.h>


int abc;

int main() {

printf("Main function\n");

printf("abc=%d\n",abc);

return 0;

}


obj.c

#include <stdio.h>


extern int abc;

__attribute__((constructor))

void pre_func(void) {

printf("[constructor] will be called before main\n");

abc = 3;

}


(1) compile only main.c

$ gcc main.c

$ ./a.out

Main function

abc=0


Compared with abc=0, we can initialize abc using __attribute__((constructor)), since it is called before main()

(2) compile with constructor

$ gcc main.c obj.c

$ ./a.out

[constructor] will be called before main

Main function

abc=3