R&D/OS

C Language Constructors and Destructors with GCC

sunshout 2015. 6. 23. 19:56

Constructor 와 Destructor 는 main 함수가 실행되기 전에 호출되는 special function 이다.

main function 이 load 되기 전에 __libc_csu_init 함수에서 constructor 들이 호출된다.


포멧:

__attribute__((constructor))

__attribute__((destructor))

__attribute__(constructor (PRIORITY)))

__attribute__(destructor (PRIORITY)))


예제:

#include <stdio.h>


void begin (void) __attribute__((constructor));

void end (void) __attribute__((destructor));


int main()

{

    printf("\nmain function\n");

    return 0;

}


void begin()

{

    printf("\nIn begin\n");

}


void end()

{

    printf("\nIn end\n");

}


실행 결과:

root@cnode02-m:~/test# ./a.out


In begin


main function


In end


(GDB 결과)
(gdb) b begin
Breakpoint 1 at 0x400546: file test.c, line 14.
(gdb) run
Starting program: /root/test/a.out

Breakpoint 1, begin () at test.c:14
14          printf("\nIn begin\n");
(gdb) bt
#0  begin () at test.c:14
#1  0x00000000004005bd in __libc_csu_init ()
#2  0x00007ffff7a36e55 in __libc_start_main (main=0x40052d <main>, argc=1, argv=0x7fffffffe6a8,
    init=0x400570 <__libc_csu_init>, fini=<optimized out>, rtld_fini=<optimized out>,
    stack_end=0x7fffffffe698) at libc-start.c:246
#3  0x0000000000400469 in _start ()


사용 예제:

jemalloc (http://www.canonware.com/jemalloc/) 은 glibc 에서 제공하는 malloc() 함수의 개선 버전이다. shared library 로 libjemallo.so 를 dynamic link 했을 때, 기존 glic의 malloc 을 jemalloc 으로 변경하기 위해서 constructor 가 호출된다.


#  define JEMALLOC_ATTR(s) __attribute__((s))


JEMALLOC_ATTR(constructor)

static void

jemalloc_constructor(void)

{


    malloc_init();

}


JEMALLOC_ATTR(constructor)
void
register_zone(void)
{

    /*
     * If something else replaced the system default zone allocator, don't
     * register jemalloc's.
     */
    malloc_zone_t *default_zone = malloc_default_zone();
    malloc_zone_t *purgeable_zone = NULL;
    if (!default_zone->zone_name ||
        strcmp(default_zone->zone_name, "DefaultMallocZone") != 0) {
        return;
    }

 


참조: 

http://sunshout.tistory.com/1709

http://phoxis.org/2011/04/27/c-language-constructors-and-destructors-with-gcc/

http://llhuii.is-programmer.com/tag/elf