C언어에서의 생성자 및 소멸자

  • main 함수 전후로 실행됨
  • OS에서 제공하는 기능은 아니고 어플리케이션 레벨에서 main함수 전후로 실행되기때문에, exit 함수등으로 프로그램 정상종료시 소멸자가 실행되지만 프로세스 강제종료시 소멸자가 실행되지 않음
  • gcc 제공기능이라 비쥬얼 스튜디오에서 안된다.
  • 여러개의 생성자를 사용 가능하며 prioirity로 순서 지정 가능(0 ~ 100번은 예약된 우선순위라 101번부터 지정가능)
#include <stdio.h>

void __attribute__((constructor (101))) my_constructor1(void) {
    printf("this is my_constructor1()\n");
}

void __attribute__((constructor (102))) my_constructor2(void) {
    printf("this is my_constructor2()\n");
}


void __attribute__((destructor (102))) my_destructor1(void) {
    printf("this is my_destructor1()\n");

}

void __attribute__((destructor (101))) my_destructor2(void) {
    printf("this is my_destructor2()\n");
}


int main(void) {

    printf("this is main()\n");

    return 0;
}
/*
this is my_constructor1()
this is my_constructor2()
this is main()
this is my_destructor1()
this is my_destructor2()
*/

'C&C++' 카테고리의 다른 글

Errno Setting Function List  (0) 2024.01.17
CMake Syntax  (0) 2020.01.21
How To Use Unit Test In C++  (0) 2020.01.13
WINAPI How To Hook ConnectEx  (0) 2019.11.06
WINAPI DLL_PROCESS_DETACH  (1) 2019.08.08

+ Recent posts