본문 바로가기
IT/programming

[C/C++] GCC C언어 constructor/destructor, 생성자/소멸자

by 어느해겨울 2022. 9. 7.

GCC C언어 constructor/destructor, 생성자/소멸자 

 

GCC 계열의 C 컴파일러도 C++의 constructor/destructor와 유사한 동작을 수행할 수 있다.
entry는 당연히 main() 부터 이지만 __attribute__ 의 constructor/destructor 키워드를 사용하면 main() 실행 전과 후 함수가 호출되는 것을 확인할 수 있고, priority를 지정하여 여러개의 함수를 우선순위에 맞춰 실행할 수도 있다.

priority는 0~100까지 reserved되어있으니 그 외의 숫자를 사용하면 되고 priority 사용은 필수가 아니다.

 

소스코드

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>


volatile sig_atomic_t is_exit_loop = 0;

char *g_ptr_arr = NULL;


/* priority 지정 X
__attribute__((constructor)) void func_constructor(void) {
    printf("func_constructor() called\n");

    return ;
}
*/

__attribute__((constructor (101))) void func_constructor_1(void) {
    printf("func_constructor() #1 called\n");

    return ;
}

__attribute__((constructor (102))) void func_constructor_2(void) {
    printf("func_constructor() #2 called\n");

    return ;
}


__attribute__((destructor (101))) void func_destructor_1(void) {
    printf("func_destructor() #1 called\n");
    if( g_ptr_arr != NULL ) {
        free(g_ptr_arr);
        g_ptr_arr = NULL;
    }

    return ;
}

__attribute__((destructor (102))) void func_destructor_2(void) {
    printf("func_destructor() #2 called\n");

    return ;
}

static void func_sig_handle(int _sig) {
    is_exit_loop = 1;

    return ;
}


int main(void) {
    signal(SIGINT, func_sig_handle);

    g_ptr_arr = (char *)malloc(20);

    while( !is_exit_loop ) {
        sleep(1);
    }

    return 0;
}

 

결과

func_constructor() #1 called
func_constructor() #2 called


^Cfunc_destructor() #2 called
func_destructor() #1 called

결과를 보면 constructor는 1-2 순서로, destructor는 2-1 순서로 수행되는 것을 확인할 수 있다.

댓글